CLAUDE.md rules for Express 5 APIs in TypeScript with ordered middleware, automatic async error forwarding, schema validation and one safe error response shape.
.claude/rules/claude-nodejs-expert.md. Downloaded files need to be placed in that repository path.---
paths:
- "**/*"
---
# Node.js Backend Conventions (Express + TypeScript)
Applies to: the Node.js HTTP API in this repository, built with Express and TypeScript.
Version baseline: checked against Express 5.x, Node.js 20+ (Express 5 requires Node 18+) and TypeScript 5.9. Read `package.json`. If the project is still on Express 4, async errors are NOT forwarded automatically, so keep explicit `next(err)` handling there.
## Layout
Follow the existing structure. The usual split is:
```
src/
├── config/ # env parsing and validation (fail fast at startup)
├── routes/ # routers: path + middleware + controller wiring
├── controllers/ # HTTP in/out only
├── services/ # business logic, no req/res
├── middleware/ # auth, validation, error handler
├── types/
└── app.ts # createApp(), no listen() so tests can import it
```
Start the server in a separate `server.ts` so tests can import `createApp()` without opening a port.
## App setup
- Order matters: security headers and CORS first, then body parsers, routes, a 404 handler, and the error handler last.
- Set an explicit CORS allowlist from config. Never reflect any origin when `credentials: true`.
- Choose JSON body limits deliberately for the API's payloads. Don't copy large defaults.
```ts
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import { config } from './config';
import { userRoutes } from './routes/users';
import { errorHandler, notFound } from './middleware/errors';
export function createApp() {
const app = express();
app.use(helmet());
app.use(cors({ origin: config.corsOrigins }));
app.use(express.json({ limit: '100kb' }));
app.use('/api/users', userRoutes);
app.use(notFound);
app.use(errorHandler);
return app;
}
```
## Controllers (Express 5)
In Express 5, a rejected promise or a thrown error in an async handler is passed to `next(err)` automatically, so don't wrap every handler in `try/catch`. Catch only errors you can turn into a specific response.
```ts
import type { Request, Response } from 'express';
import { AppError } from '../middleware/errors';
import { CreateUserSchema } from '../types/user'; // Zod schema
import type { UserService } from '../services/user-service';
export class UserController {
constructor(private readonly users: UserService) {}
getUser = async (req: Request<{ id: string }>, res: Response) => {
const user = await this.users.findById(req.params.id);
if (!user) throw new AppError(404, 'User not found');
res.json({ data: user });
};
createUser = async (req: Request, res: Response) => {
const input = CreateUserSchema.parse(req.body); // or validated by middleware
const user = await this.users.create(input);
res.status(201).json({ data: user });
};
}
```
- Validate `req.body`, `req.params` and `req.query` with a schema (for example Zod 4) before they reach a service. In Express 5 `req.query` is a getter, so store parsed values on `res.locals` or pass them on instead of reassigning `req.query`.
- Never pass `req.body` straight into an ORM `create` call.
## Errors
```ts
// middleware/errors.ts
import type { ErrorRequestHandler, RequestHandler } from 'express';
import { ZodError } from 'zod';
import { logger } from '../utils/logger'; // project's structured logger (e.g. pino)
export class AppError extends Error {
constructor(public readonly statusCode: number, message: string) {
super(message);
this.name = 'AppError';
}
}
export const errorHandler: ErrorRequestHandler = (err, req, res, _next) => {
if (err instanceof AppError) {
res.status(err.statusCode).json({ error: err.message });
return;
}
if (err instanceof ZodError) {
res.status(400).json({ error: 'Validation failed', issues: err.issues });
return;
}
logger.error({ err, path: req.path }, 'unhandled error');
res.status(500).json({ error: 'Internal server error' });
};
export const notFound: RequestHandler = (_req, res) => {
res.status(404).json({ error: 'Not found' });
};
```
- Keep one error response shape. Never send stack traces or internal messages for 500s.
- Use a structured logger (for example pino) instead of `console.error` in request paths.
## Process
- Read configuration once at startup and validate it. Crash early with a clear message when a required variable is missing.
- Handle `SIGTERM` by calling `server.close()` and closing database pools before exit.
## Tests
- Test routes with `supertest` (or `fetch` against an ephemeral port) using `createApp()`, and mock services at the boundary.
## Verify before finishing
Run when available: `npx tsc --noEmit`, `npx eslint .`, and the project test command (`npm test`).
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Claude
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Claude Code works on an Express + TypeScript API with this file loaded as a project rule (for example .claude/rules/node-api.md scoped to src/**/*.ts).
Add POST /api/users (email, name) and GET /api/users/:id. Express is ^5.1.0, Zod 4 is installed, and src/middleware/errors.ts has an AppError class. Controllers currently wrap every handler in try/catch and pass req.body straight to prisma.user.create.
Illustrative; not a recorded model run. Async controllers without blanket try/catch (Express 5 forwards rejections), a Zod schema validating the body before the service call, AppError(404) thrown for a missing user, an error handler that maps AppError and ZodError (using .issues) and returns a generic 500 without leaking messages, notFound and errorHandler registered last, createApp separated from listen for supertest, and tsc/eslint/test results.
Claude Code loads persistent project instructions from CLAUDE.md files and from Markdown rules in .claude/rules/. Rules can be scoped to file paths with a paths frontmatter field, and CLAUDE.md can import other files with @path syntax. The rules in this directory are written as plain instruction prompts: in Claude Code, save them as CLAUDE.md or .claude/rules/ content; in Claude.ai or the Claude API, use the same text as project instructions or a system prompt instead.
.claude/rules/claude-nodejs-expert.mdStarting point, not a tested configuration for your repository. Loaded when Claude Code works with files matching paths. Review the instructions, adapt the file paths and run your project's existing checks.
---
paths:
- "**/*"
---
# Node.js Backend Conventions (Express + TypeScript)
Applies to: the Node.js HTTP API in this repository, built with Express and TypeScript.
Version baseline: checked against Express 5.x, Node.js 20+ (Express 5 requires Node 18+) and TypeScript 5.9. Read `package.json`. If the project is still on Express 4, async errors are NOT forwarded automatically, so keep explicit `next(err)` handling there.
## Layout
Follow the existing structure. The usual split is:
```
src/
├── config/ # env parsing and validation (fail fast at startup)
├── routes/ # routers: path + middleware + controller wiring
├── controllers/ # HTTP in/out only
├── services/ # business logic, no req/res
├── middleware/ # auth, validation, error handler
├── types/
└── app.ts # createApp(), no listen() so tests can import it
```
Start the server in a separate `server.ts` so tests can import `createApp()` without opening a port.
## App setup
- Order matters: security headers and CORS first, then body parsers, routes, a 404 handler, and the error handler last.
- Set an explicit CORS allowlist from config. Never reflect any origin when `credentials: true`.
- Choose JSON body limits deliberately for the API's payloads. Don't copy large defaults.
```ts
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import { config } from './config';
import { userRoutes } from './routes/users';
import { errorHandler, notFound } from './middleware/errors';
export function createApp() {
const app = express();
app.use(helmet());
app.use(cors({ origin: config.corsOrigins }));
app.use(express.json({ limit: '100kb' }));
app.use('/api/users', userRoutes);
app.use(notFound);
app.use(errorHandler);
return app;
}
```
## Controllers (Express 5)
In Express 5, a rejected promise or a thrown error in an async handler is passed to `next(err)` automatically, so don't wrap every handler in `try/catch`. Catch only errors you can turn into a specific response.
```ts
import type { Request, Response } from 'express';
import { AppError } from '../middleware/errors';
import { CreateUserSchema } from '../types/user'; // Zod schema
import type { UserService } from '../services/user-service';
export class UserController {
constructor(private readonly users: UserService) {}
getUser = async (req: Request<{ id: string }>, res: Response) => {
const user = await this.users.findById(req.params.id);
if (!user) throw new AppError(404, 'User not found');
res.json({ data: user });
};
createUser = async (req: Request, res: Response) => {
const input = CreateUserSchema.parse(req.body); // or validated by middleware
const user = await this.users.create(input);
res.status(201).json({ data: user });
};
}
```
- Validate `req.body`, `req.params` and `req.query` with a schema (for example Zod 4) before they reach a service. In Express 5 `req.query` is a getter, so store parsed values on `res.locals` or pass them on instead of reassigning `req.query`.
- Never pass `req.body` straight into an ORM `create` call.
## Errors
```ts
// middleware/errors.ts
import type { ErrorRequestHandler, RequestHandler } from 'express';
import { ZodError } from 'zod';
import { logger } from '../utils/logger'; // project's structured logger (e.g. pino)
export class AppError extends Error {
constructor(public readonly statusCode: number, message: string) {
super(message);
this.name = 'AppError';
}
}
export const errorHandler: ErrorRequestHandler = (err, req, res, _next) => {
if (err instanceof AppError) {
res.status(err.statusCode).json({ error: err.message });
return;
}
if (err instanceof ZodError) {
res.status(400).json({ error: 'Validation failed', issues: err.issues });
return;
}
logger.error({ err, path: req.path }, 'unhandled error');
res.status(500).json({ error: 'Internal server error' });
};
export const notFound: RequestHandler = (_req, res) => {
res.status(404).json({ error: 'Not found' });
};
```
- Keep one error response shape. Never send stack traces or internal messages for 500s.
- Use a structured logger (for example pino) instead of `console.error` in request paths.
## Process
- Read configuration once at startup and validate it. Crash early with a clear message when a required variable is missing.
- Handle `SIGTERM` by calling `server.close()` and closing database pools before exit.
## Tests
- Test routes with `supertest` (or `fetch` against an ephemeral port) using `createApp()`, and mock services at the boundary.
## Verify before finishing
Run when available: `npx tsc --noEmit`, `npx eslint .`, and the project test command (`npm test`).
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Imports with @path can nest up to four hops deep, according to the docs. Claude Code can read AGENTS.md as project instructions without extra configuration, but by default only when there is no CLAUDE.md in the working directory or above it. The docs list this behavior for version 2.1.277 and later and describe a setting (claude-md-and-agents-md) that loads both files. If you maintain AGENTS.md for other tools, you can also import it from CLAUDE.md with @AGENTS.md.
Documentation checked 2026-11-05: Claude Code docs: Manage Claude's memory
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.