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.
.cursor/rules/nodejs-express-api-development.mdc. Downloaded files need to be placed in that repository path.---
description: "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."
globs: "**/*"
alwaysApply: false
---
# Node.js Express API Development
Applies to: HTTP APIs built with Express and TypeScript: app setup, routing, validation and error handling.
Version baseline: checked against the Express 5 documentation (5.x is the current major and requires Node.js 18+) and Zod 4. Read `package.json` first. On Express 4, async errors are not forwarded automatically: wrap async handlers or call `next(error)` yourself. On Zod 3, use `error.errors` and `z.string().email()`.
## Project structure
```
src/
├── app.ts # createApp(): middleware, routes, error handler
├── server.ts # listen(), graceful shutdown
├── config.ts # validated environment variables
├── routes/ # routers: URL + middleware + controller wiring
├── controllers/ # HTTP in/out only
├── services/ # business logic, no req/res
├── middleware/ # validate, auth, errorHandler, requestLogger
└── lib/logger.ts
```
Keep `createApp()` free of `listen()` so tests can import the app without opening a port.
## App setup
```ts
// src/app.ts
import express, { type Express } from 'express'
import helmet from 'helmet'
import cors from 'cors'
import { config } from './config'
import { requestLogger } from './middleware/requestLogger'
import { errorHandler, notFound } from './middleware/errorHandler'
import { router } from './routes'
export function createApp(): Express {
const app = express()
app.disable('x-powered-by')
app.use(helmet())
app.use(cors({ origin: config.corsOrigins, credentials: true }))
app.use(express.json({ limit: '100kb' }))
app.use(requestLogger)
app.get('/health', (_req, res) => { res.json({ status: 'ok' }) })
app.use('/api', router)
app.use(notFound)
app.use(errorHandler) // last
return app
}
```
- Set `cors` origins from configuration; never reflect arbitrary origins when `credentials: true`.
- Choose the JSON body limit for the API's real payloads and document it; the default is 100kb.
- Use `compression()` only if a proxy or CDN in front of the app does not already compress responses.
## Handlers: no try/catch boilerplate on Express 5
Express 5 passes a rejected promise or a thrown error from an async handler or middleware to `next(err)`. Write handlers without `try`/`catch` unless you can recover. A promise you start but do not return still needs its own `.catch(next)`.
```ts
// src/controllers/userController.ts
import type { Request, Response } from 'express'
import { AppError } from '../middleware/errorHandler'
import type { UserService } from '../services/userService'
export function userController(users: UserService) {
return {
list: async (_req: Request, res: Response) => {
const { page, limit } = res.locals.query as { page: number; limit: number }
res.json(await users.findAll({ page, limit }))
},
get: async (req: Request<{ id: string }>, res: Response) => {
const user = await users.findById(req.params.id)
if (!user) throw new AppError(404, 'User not found')
res.json(user)
},
create: async (_req: Request, res: Response) => {
res.status(201).json(await users.create(res.locals.body))
},
}
}
```
## Validation
In Express 5, `req.query` is a getter and cannot be reassigned. Store parsed values in `res.locals` and read them from there.
```ts
// src/middleware/validate.ts
import type { Request, Response, NextFunction } from 'express'
import { z } from 'zod'
type Part = 'body' | 'query' | 'params'
export function validate(part: Part, schema: z.ZodType) {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req[part])
if (!result.success) {
res.status(400).json({ error: 'Validation failed', issues: result.error.issues })
return
}
res.locals[part] = result.data
next()
}
}
export const createUserBody = z.object({
email: z.email(),
name: z.string().trim().min(1),
password: z.string().min(12),
})
export const listQuery = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
})
```
Route wiring: `router.post('/users', validate('body', createUserBody), users.create)`.
Never return password hashes or internal fields; map service results to response DTOs.
## Error handling
```ts
// src/middleware/errorHandler.ts
import type { Request, Response, NextFunction } from 'express'
import { logger } from '../lib/logger'
export class AppError extends Error {
constructor(public readonly statusCode: number, message: string, options?: ErrorOptions) {
super(message, options)
this.name = 'AppError'
}
}
export function notFound(_req: Request, res: Response) {
res.status(404).json({ error: 'Not found' })
}
export function errorHandler(err: unknown, req: Request, res: Response, next: NextFunction) {
if (res.headersSent) return next(err)
if (err instanceof AppError) {
res.status(err.statusCode).json({ error: err.message })
return
}
logger.error({ err, method: req.method, path: req.path }, 'unhandled error')
res.status(500).json({ error: 'Internal server error' })
}
```
- The error handler has four parameters; Express identifies it by arity, so keep `next` even if unused.
- Do not send `err.message` of unexpected errors to clients, in any environment that is reachable from outside.
## Express 5 route syntax
Wildcards must be named (`/files/*splat`, root `/{*splat}`) and optional parts use braces (`/:file{.:ext}`); the old `?` and bare `*` forms throw at startup.
## Verify before finishing
- `npx tsc --noEmit` and the project's lint pass.
- Integration tests with `supertest` (or `fetch` against `createApp().listen(0)`): invalid body returns 400 with `issues`; unknown route returns 404 JSON; a handler that throws returns 500 without a stack trace; a rejected promise in an async handler reaches the error handler.
- `npm ls express` shows the major version the guidance assumes.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Upgrading an Express 4 TypeScript API to Express 5 and tightening validation and error responses.
We moved to express@5. Controllers wrap every async handler in try/catch + next(error), validate() assigns req.query = parsed, the error handler returns err.message in non-production, and routes use '/files/*'. Update the code.
Illustrative; not a recorded model run. Controllers without try/catch that throw AppError(404, ...) for expected failures; validate(part, schema) using safeParse, returning 400 with issues and storing parsed data in res.locals; error handler with four parameters that checks res.headersSent, maps AppError, logs unexpected errors with method and path and returns a generic 500; '/files/*splat'; CORS origins from config; createApp without listen().
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/nodejs-express-api-development.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Node.js Express API Development: Express 5, TypeScript and Zod Validation project conventions"
globs: "**/*"
alwaysApply: false
---
# Node.js Express API Development
Applies to: HTTP APIs built with Express and TypeScript: app setup, routing, validation and error handling.
Version baseline: checked against the Express 5 documentation (5.x is the current major and requires Node.js 18+) and Zod 4. Read `package.json` first. On Express 4, async errors are not forwarded automatically: wrap async handlers or call `next(error)` yourself. On Zod 3, use `error.errors` and `z.string().email()`.
## Project structure
```
src/
├── app.ts # createApp(): middleware, routes, error handler
├── server.ts # listen(), graceful shutdown
├── config.ts # validated environment variables
├── routes/ # routers: URL + middleware + controller wiring
├── controllers/ # HTTP in/out only
├── services/ # business logic, no req/res
├── middleware/ # validate, auth, errorHandler, requestLogger
└── lib/logger.ts
```
Keep `createApp()` free of `listen()` so tests can import the app without opening a port.
## App setup
```ts
// src/app.ts
import express, { type Express } from 'express'
import helmet from 'helmet'
import cors from 'cors'
import { config } from './config'
import { requestLogger } from './middleware/requestLogger'
import { errorHandler, notFound } from './middleware/errorHandler'
import { router } from './routes'
export function createApp(): Express {
const app = express()
app.disable('x-powered-by')
app.use(helmet())
app.use(cors({ origin: config.corsOrigins, credentials: true }))
app.use(express.json({ limit: '100kb' }))
app.use(requestLogger)
app.get('/health', (_req, res) => { res.json({ status: 'ok' }) })
app.use('/api', router)
app.use(notFound)
app.use(errorHandler) // last
return app
}
```
- Set `cors` origins from configuration; never reflect arbitrary origins when `credentials: true`.
- Choose the JSON body limit for the API's real payloads and document it; the default is 100kb.
- Use `compression()` only if a proxy or CDN in front of the app does not already compress responses.
## Handlers: no try/catch boilerplate on Express 5
Express 5 passes a rejected promise or a thrown error from an async handler or middleware to `next(err)`. Write handlers without `try`/`catch` unless you can recover. A promise you start but do not return still needs its own `.catch(next)`.
```ts
// src/controllers/userController.ts
import type { Request, Response } from 'express'
import { AppError } from '../middleware/errorHandler'
import type { UserService } from '../services/userService'
export function userController(users: UserService) {
return {
list: async (_req: Request, res: Response) => {
const { page, limit } = res.locals.query as { page: number; limit: number }
res.json(await users.findAll({ page, limit }))
},
get: async (req: Request<{ id: string }>, res: Response) => {
const user = await users.findById(req.params.id)
if (!user) throw new AppError(404, 'User not found')
res.json(user)
},
create: async (_req: Request, res: Response) => {
res.status(201).json(await users.create(res.locals.body))
},
}
}
```
## Validation
In Express 5, `req.query` is a getter and cannot be reassigned. Store parsed values in `res.locals` and read them from there.
```ts
// src/middleware/validate.ts
import type { Request, Response, NextFunction } from 'express'
import { z } from 'zod'
type Part = 'body' | 'query' | 'params'
export function validate(part: Part, schema: z.ZodType) {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req[part])
if (!result.success) {
res.status(400).json({ error: 'Validation failed', issues: result.error.issues })
return
}
res.locals[part] = result.data
next()
}
}
export const createUserBody = z.object({
email: z.email(),
name: z.string().trim().min(1),
password: z.string().min(12),
})
export const listQuery = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
})
```
Route wiring: `router.post('/users', validate('body', createUserBody), users.create)`.
Never return password hashes or internal fields; map service results to response DTOs.
## Error handling
```ts
// src/middleware/errorHandler.ts
import type { Request, Response, NextFunction } from 'express'
import { logger } from '../lib/logger'
export class AppError extends Error {
constructor(public readonly statusCode: number, message: string, options?: ErrorOptions) {
super(message, options)
this.name = 'AppError'
}
}
export function notFound(_req: Request, res: Response) {
res.status(404).json({ error: 'Not found' })
}
export function errorHandler(err: unknown, req: Request, res: Response, next: NextFunction) {
if (res.headersSent) return next(err)
if (err instanceof AppError) {
res.status(err.statusCode).json({ error: err.message })
return
}
logger.error({ err, method: req.method, path: req.path }, 'unhandled error')
res.status(500).json({ error: 'Internal server error' })
}
```
- The error handler has four parameters; Express identifies it by arity, so keep `next` even if unused.
- Do not send `err.message` of unexpected errors to clients, in any environment that is reachable from outside.
## Express 5 route syntax
Wildcards must be named (`/files/*splat`, root `/{*splat}`) and optional parts use braces (`/:file{.:ext}`); the old `?` and bare `*` forms throw at startup.
## Verify before finishing
- `npx tsc --noEmit` and the project's lint pass.
- Integration tests with `supertest` (or `fetch` against `createApp().listen(0)`): invalid body returns 400 with `issues`; unknown route returns 404 JSON; a handler that throws returns 500 without a stack trace; a rejected promise in an async handler reaches the error handler.
- `npm ls express` shows the major version the guidance assumes.
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.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.