API Endpoints (Netlify Functions)
Relevant source files
The following files were used as context for generating this wiki page:The serverless backend for BMSview is built using Netlify Functions, which handle all API logic, from AI-powered analysis to database interactions and proxying external services. These functions are written in Node.js (using CommonJS modules with a .cjs extension) and TypeScript, providing a scalable and maintainable backend architecture. The functions are the bridge between the React frontend and backend services like MongoDB and the Google Gemini API.
The overall system architecture is designed to be local-first, with Netlify Functions serving as the authoritative source for data synchronization and complex processing tasks that cannot be performed on the client. For more details on the data synchronization strategy, see the Local-First Sync Migration section in the main project documentation.
Sources: README.md:113-115, CODEBASE.md:10-12, GEMINI.md:21-24, CONTRIBUTING.md:143-145
Function Architecture and Configuration
Netlify Functions are configured in the netlify.toml file and located in the netlify/functions/ directory. The backend functions primarily use CommonJS (require/module.exports), while some, like solar-estimate.ts, are written in TypeScript and bundled during deployment.
Sources: CODEBASE.md:10-12, README.md:83-87
Configuration
The netlify.toml file specifies the directory where the serverless functions are located.
# netlify.toml
[functions]
directory = "netlify/functions"
Sources: netlify.toml
Module System
A strict separation of module systems is enforced:
- Backend (
.cjsfiles): Use CommonJS (require/module.exports). - Frontend (
.ts,.tsxfiles): Use ES Modules (import/export).
This separation is critical to prevent build and runtime errors.
Sources: CONTRIBUTING.md:143-145, CODEBASE.md:10-12
Core Utilities
Several shared utility modules are used across the functions to ensure consistency in logging, error handling, and database connections.
| Utility | File Path | Purpose |
|---|---|---|
| Logger | utils/logger.cjs | Provides structured JSON logging. |
| CORS | utils/cors.cjs | Manages Cross-Origin Resource Sharing policies based on environment. |
| MongoDB Client | utils/mongodb.cjs | A helper (getCollection()) to manage database connections and pooling. |
| Retry Logic | utils/retry.cjs | Wrappers for operations that interact with external services to handle transient failures. |
Sources: CONTRIBUTING.md:146-149, MAJOR_FIX_UPDATE_SUMMARY.md:50-58, CODEBASE.md:26-31
Core Endpoints
These endpoints form the main functionality of the BMSview application, handling screenshot analysis and insights generation.
analyze Endpoint
The analyze endpoint is responsible for processing BMS screenshot uploads. It handles environment validation, deduplication of previously analyzed images, and orchestration of the AI analysis pipeline. It supports both a fast synchronous flow and a more robust asynchronous flow for bulk uploads.
Sources: GEMINI.md:62-68, COMPLETE_FIX_SUMMARY.md:29-32
The following diagram illustrates the two processing flows available in the analyze endpoint.
Key features of the analyze endpoint include:
- Environment Validation: Checks for
GEMINI_API_KEYandMONGODB_URIbefore processing. - Graceful Degradation: Non-critical failures (like deduplication checks) log a warning but do not terminate the request.
- Structured Error Responses: Returns specific HTTP status codes (400, 408, 503) and error codes (
analysis_timeout,database_unavailable) for clear client-side handling. - Audit Logging: Logs
force_reanalysisevents for security and traceability.
Sources: COMPLETE_FIX_SUMMARY.md:34-45, MAJOR_FIX_UPDATE_SUMMARY.md:70-78
generate-insights-with-tools Endpoint
This endpoint powers the "Ultimate AI Battery Guru" feature. It uses a ReAct (Reasoning and Acting) loop, allowing the Gemini AI model to dynamically call predefined "tools" to fetch additional data during its analysis. This is more powerful than providing a static context.
Sources: REACT_LOOP_README.md:10-12, GEMINI.md:15-19
The ReAct loop works as follows:
This endpoint also supports both synchronous and background processing modes to handle queries of varying complexity.
Sources: FINAL_VERIFICATION.md:38-61
Solar Integration Endpoint
solar-estimate Endpoint
This endpoint acts as a server-side proxy for the external Solar Charge Estimator API. This is done to protect API keys and manage requests from a central point. It is a TypeScript-based function.
Sources: README.md:73-75, CODEBASE.md:12-13
Endpoint: GET /.netlify/functions/solar-estimate
The endpoint forwards requests to the Solar Charge Estimator API, which requires location and panel specifications.
The data flow for a solar estimate request is shown below.
Sources: README.md:73-81
Query Parameters
The endpoint accepts the following query parameters, which are then passed to the external API.
| Parameter | Type | Description | Example |
|---|---|---|---|
location | string | Zip code or GPS coordinates for the solar estimate. | 80942 |
panelWatts | number | The total wattage of the solar panel array. | 400 |
startDate | string | The start date for the estimate range (YYYY-MM-DD). | 2025-10-29 |
endDate | string | The end date for the estimate range (YYYY-MM-DD). | 2025-10-31 |
Sources: README.md:76-81
Administrative and Utility Endpoints
BMSview includes several functions for administrative tasks, diagnostics, and data synchronization.
admin-diagnostics
This function runs a suite of tests against critical application components, including database connectivity, API services (Gemini, Weather), and the analysis pipelines. It is designed to run all tests and report structured results for each, even if some tests fail. This prevents a single failure from halting the entire diagnostic run.
Sources: COMPLETE_FIX_SUMMARY.md:19-28, diagnostics/TROUBLESHOOTING.md:3-5
Sync Endpoints
To support the local-first architecture, a set of sync-related functions exist:
sync-metadata: Provides metadata (timestamps, record counts) for data collections.sync-incremental: Returns documents that have been updated since a given timestamp.migrate-add-sync-fields: A one-time migration script to prepare the database for the sync layer.
These endpoints are crucial for the client-side SyncManager to efficiently synchronize local (IndexedDB) and remote (MongoDB) data stores.
Sources: README.md:154-184, GEMINI.md:40-43
Conclusion
The Netlify Functions in BMSview provide a robust, scalable, and secure serverless backend. They encapsulate all server-side logic, from complex, multi-step AI analysis with the ReAct pattern to simple API proxying. The clear separation of concerns, use of shared utilities, and detailed configuration allow for a maintainable and powerful system that supports the application's core features.
Sources: GEMINI.md:21-24, README.md:113-115