Node.js API Builder Skill
Process
- Decide the host: Next.js Route Handler (
src/app/api/<resource>/route.ts) for app-coupled endpoints, or a standalone service file undersrc/server/routes/if this repo has a separate Node/Express backend — checksrc/server/for an existing pattern first. - Define the schema first — write the
zodschema for the request body/query/params before writing the handler logic. - Use route-handler-template.ts as the starting structure.
- Status codes:
200success,201created,400validation error,401unauthenticated,403unauthorized,404not found,409conflict,500unexpected — never return200with an error payload. - Auth check happens first in the handler, before any validation or DB call, to fail fast and avoid unnecessary work.
- Errors: catch and return the structured shape
{ error: { code: string; message: string } }; log the original error server-side with the structured logger, don't leak internals to the client. - Add a test hitting the handler directly (or via
supertest/integration test) covering: success case, validation failure, auth failure.
Checklist
-
zodschema validates all external input - Correct HTTP status codes used
- Auth checked before business logic
- Errors logged server-side, sanitized client-side
- Test covers success + at least one failure path