| name | adding-backend-feature |
| description | Add a new API endpoint or backend feature to the Cloudflare Worker. Use when adding routes to src/worker.js, new FoxESS API integrations, or shared helpers in src/lib/foxess.js. |
| user-invocable | true |
| argument-hint | [e.g. 'add battery history endpoint' or 'add rate limiting'] |
Adding a Backend Feature
You are adding a new API endpoint or backend capability to the FoxESS Cloudflare Worker.
Before Starting
- Read
src/worker.js to understand the routing pattern
- Read
src/lib/foxess.js to understand shared helpers
- Read
wrangler.jsonc for Worker configuration
Architecture
src/worker.js — single entry point, routes requests by url.pathname
src/lib/foxess.js — shared helpers (FoxESS API calls, auth, CORS, caching)
- Static assets from
public/ served via env.ASSETS.fetch(request)
- All
/api/* routes handled by the Worker; everything else falls through to static assets
Adding a New API Endpoint
-
Add route in src/worker.js following the existing if/else if pattern:
} else if (path === '/api/your-endpoint') {
if (!validateApiKey(request, env)) {
response = new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401, headers: { 'Content-Type': 'application/json' }
});
} else {
response = new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' }
});
}
-
Add shared helpers to src/lib/foxess.js if reusable:
- Export the function:
export async function yourHelper(env) { ... }
- Import in worker.js: add to the existing import statement
-
Use caching if calling an external API:
var ttl = parseInt(env.CACHE_TTL) || 60;
var cached = await cachedFetch('unique-cache-key', function() {
return yourFetchFunction(env);
}, ttl);
-
Auth: Use validateApiKey(request, env) for protected endpoints. Only /api/health is public.
-
CORS: Handled automatically at the end of the fetch handler — no per-route CORS needed.
FoxESS API Integration
When calling a new FoxESS endpoint:
- Use
createFoxESSHeaders(path, env.FOXESS_API_KEY) for auth headers
- Base URL:
https://www.foxesscloud.com
- POST with JSON body, include
sn: env.FOXESS_DEVICE_SN
- Signature uses literal
\r\n (escaped, not actual CRLF) — see generateSignature()
Adding Environment Variables
- Add in Cloudflare Dashboard (Settings > Variables and Secrets)
- Access via
env.VARIABLE_NAME in Worker code
- Document in README.md and AGENTS.md environment variables tables
After Implementation
- Test locally with
npx wrangler dev if possible
- Update API Routes tables in README.md and AGENTS.md
- Ask the user if they want to commit and push
- If committing, use a concise message with
Co-Authored-By: Codex Opus 4.5 <noreply@anthropic.com>
- Run
/reflect to update documentation