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.jsto understand the routing pattern - Read
src/lib/foxess.jsto understand shared helpers - Read
wrangler.jsoncfor Worker configuration
Architecture
src/worker.js— single entry point, routes requests byurl.pathnamesrc/lib/foxess.js— shared helpers (FoxESS API calls, auth, CORS, caching)- Static assets from
public/served viaenv.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.jsfollowing the existingif/else ifpattern:} 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 { // Your logic here response = new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }); }Add shared helpers to
src/lib/foxess.jsif reusable:- Export the function:
export async function yourHelper(env) { ... } - Import in worker.js: add to the existing import statement
- Export the function:
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/healthis 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) — seegenerateSignature()
Adding Environment Variables
- Add in Cloudflare Dashboard (Settings > Variables and Secrets)
- Access via
env.VARIABLE_NAMEin Worker code - Document in README.md and CLAUDE.md environment variables tables
After Implementation
- Test locally with
npx wrangler devif possible - Update API Routes tables in README.md and CLAUDE.md
- Ask the user if they want to commit and push
- If committing, use a concise message with
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> - Run
/reflectto update documentation