Skip to content

project rulesBackend and APIsnodeexpress

Node Express Rules

Project rules for Express services: routes, services and data layers, schema validation, central error middleware, structured logs and supertest.

npx workspacetemplates add node-express-rules --tool claude-code

Writes 1 file to your project root

CLAUDE.mdadd to your file26 lines · 1.4 KBFile
# Project rules: Express

## Structure
- Split `app.ts` (builds and exports the Express app) from `server.ts` (listens and handles shutdown). Tests import the app only.
- Layers per feature: `routes` map URLs, `controllers` handle req and res, `services` hold logic, `repositories` talk to the database. Lower layers never import `req` or `res`.

## Requests
- Validate `body`, `params` and `query` with Zod or similar in a middleware before the handler runs. Trust nothing past that point unvalidated.
- Add `helmet`, a body size limit and rate limiting on public routes. Configure CORS with an explicit origin list.

## Errors
- Throw typed errors (`NotFoundError`, `ValidationError`) carrying a status. Wrap async handlers, or use Express 5 which forwards rejections, so none escape.
- One error middleware, registered last, returns `{ error: { code, message } }`. It logs the stack and hides it from clients.

## Logging and config
- Use pino with a request id; never `console.log` in code that ships. Never log tokens or passwords.
- Parse environment variables once at startup into a typed config object and fail fast if one is missing.

## Runtime
- Handle SIGTERM: stop accepting connections, finish in-flight requests, close the database pool.

## Tests
- Vitest or Jest with supertest against the exported app. Mock only at the repository boundary.

## Before finishing
Run `npm run lint`, `npm run typecheck` and `npm test`.

What it does

Express does not impose structure, so a service often grows into route files that validate, query and format in one place. These rules separate those jobs and give errors a single exit.

They also cover the production basics an agent forgets: request validation, structured logging, graceful shutdown and tests that never open a real port.

Example

you › Add PATCH /users/:id to update a display name

agent › The agent adds a Zod schema middleware, a service method that throws NotFoundError for missing users, and supertest cases for 200, 400 and 404.

Questions

Does it assume TypeScript?
It is written with TypeScript in mind, but the layering and error rules apply to a JavaScript project as well.
Why split app and server files?
Importing an app that has already started listening makes tests flaky. A separate server file keeps the port out of the test run.
  • ASP.NET Core Web API Rules

    Project rulesdotnet

    Free
  • Django Rules

    Project rulespython

    Free
  • Flask Rules

    Project rulespython

    Free
  • Go Service Rules

    Project rulesgo

    Free