Cursor rules for Express 5 middleware with single-purpose factories, explicit ordering, automatic async error forwarding and a four-argument error handler.
.cursor/rules/expressjs-middleware-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for Express 5 middleware with single-purpose factories, explicit ordering, automatic async error forwarding and a four-argument error handler."
globs: "**/*"
alwaysApply: false
---
# Express.js Middleware Patterns
Applies to: Express application setup, routers and middleware (`app.ts`, `routes/**`, `middleware/**`).
Version baseline: checked against Express 5 documentation (Node.js 18+). Read `package.json` first: on Express 4, rejected promises are not forwarded to error handlers automatically, so wrap async handlers or call `next(err)` yourself.
## One job per middleware
- Each middleware does one thing: parse, authenticate, authorize, validate, rate-limit, log. Name it for what it does (`requireAuth`, `validateBody(schema)`, `requestId`).
- Write configurable middleware as a factory that returns the handler: `rateLimit({ windowMs, max })`, `requireRole('admin')`.
- A middleware either ends the response or calls `next()`, exactly once on every path. Never both.
- Pass data downstream on `res.locals` (per request) instead of mutating `req` with untyped properties. In TypeScript, if you must add to `req`, declare it with module augmentation.
## Order matters
Register in this order and keep it in one place (`createApp()`):
1. Request ID / logging
2. Security headers and CORS
3. Body parsers (`express.json()`, `express.urlencoded()`) with explicit size limits chosen for your payloads
4. Route-specific auth, validation and rate limits, attached to the routers or routes that need them
5. Routes
6. A 404 handler for unmatched routes
7. The error-handling middleware, last
In the snippets below, `verifyToken`, `ordersRouter`, `orders`, `HttpError` and `logger` stand for project modules.
```ts
import express, { type ErrorRequestHandler, type RequestHandler } from 'express';
export const requireAuth: RequestHandler = (req, res, next) => {
const token = req.get('authorization')?.replace(/^Bearer /, '');
if (!token) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
res.locals.userId = verifyToken(token); // throws on an invalid token
next();
};
export function createApp() {
const app = express();
app.use(express.json({ limit: '100kb' }));
app.use('/api/orders', requireAuth, ordersRouter);
app.use((req, res) => {
res.status(404).json({ error: 'Not found' });
});
app.use(errorHandler);
return app;
}
```
## Async errors (Express 5)
- In Express 5, a route handler or middleware that returns a rejected promise, or throws inside an `async` function, is forwarded to the error handler automatically. Do not wrap every handler in `try/catch` just to call `next(err)`.
- A promise you start but do not `await` or return is not tracked; `await` it or attach `.catch(next)`.
- Errors thrown inside callbacks (timers, event emitters) are not caught by Express; convert them to promises or call `next(err)` yourself.
```ts
ordersRouter.get('/:id', async (req, res) => {
const order = await orders.find(req.params.id); // rejection goes to errorHandler
if (!order) {
res.status(404).json({ error: 'Order not found' });
return;
}
res.json(order);
});
```
## Error-handling middleware
- Declare it with four parameters `(err, req, res, next)`; Express recognizes error handlers by arity.
- Map known error types to status codes; log unexpected errors with the request ID and return a generic message.
- If headers were already sent, delegate to Express with `next(err)`.
```ts
export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
if (res.headersSent) {
next(err);
return;
}
const status = err instanceof HttpError ? err.status : 500;
if (status >= 500) logger.error({ err, requestId: res.locals.requestId }, 'request failed');
res.status(status).json({ error: status >= 500 ? 'Internal server error' : err.message });
};
```
## Express 5 changes to watch
- `req.query` is a read-only getter; validate it into a new object instead of reassigning it.
- `req.body` is `undefined` until a body parser has run.
- Path syntax changed: wildcards must be named (`/*splat`), and optional parts use braces (`/:file{.:ext}`).
## Typing
- Type handlers with `RequestHandler` / `ErrorRequestHandler` from `express` (types from `@types/express`), or `RequestHandler<Params, ResBody, ReqBody, Query>` when you need typed params and bodies.
- Validate external input (body, query, params) with a schema library at the route boundary and use the parsed result, not the raw `req` values.
## Verify before finishing
Run these when they are available in the project:
- `npx tsc --noEmit`
- route tests with `supertest`, including: missing auth returns 401, an unmatched route returns 404, a handler that rejects returns 500 from the error handler, and order of middleware is preserved
- `npm run lint`
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
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
An Express 5 + TypeScript API has this rule attached to app and middleware files while a developer asks Cursor to protect a router and clean up error handling.
Protect /api/orders with bearer-token auth, return JSON 404s for unknown routes, and replace the try/catch-next(error) blocks in the orders router with something cleaner.
Illustrative; not a recorded model run. A requireAuth RequestHandler that responds 401 or calls next() exactly once and stores the user on res.locals; createApp registering parsers, the auth middleware on the orders router only, routes, a 404 handler and the error handler last; async route handlers with the try/catch wrappers removed because Express 5 forwards rejections; an ErrorRequestHandler with four parameters that checks res.headersSent, maps HttpError to its status and hides 5xx messages.
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/expressjs-middleware-patterns.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: "Express.js Middleware Patterns: Ordering, Async Errors and Error Handlers project conventions"
globs: "**/*"
alwaysApply: false
---
# Express.js Middleware Patterns
Applies to: Express application setup, routers and middleware (`app.ts`, `routes/**`, `middleware/**`).
Version baseline: checked against Express 5 documentation (Node.js 18+). Read `package.json` first: on Express 4, rejected promises are not forwarded to error handlers automatically, so wrap async handlers or call `next(err)` yourself.
## One job per middleware
- Each middleware does one thing: parse, authenticate, authorize, validate, rate-limit, log. Name it for what it does (`requireAuth`, `validateBody(schema)`, `requestId`).
- Write configurable middleware as a factory that returns the handler: `rateLimit({ windowMs, max })`, `requireRole('admin')`.
- A middleware either ends the response or calls `next()`, exactly once on every path. Never both.
- Pass data downstream on `res.locals` (per request) instead of mutating `req` with untyped properties. In TypeScript, if you must add to `req`, declare it with module augmentation.
## Order matters
Register in this order and keep it in one place (`createApp()`):
1. Request ID / logging
2. Security headers and CORS
3. Body parsers (`express.json()`, `express.urlencoded()`) with explicit size limits chosen for your payloads
4. Route-specific auth, validation and rate limits, attached to the routers or routes that need them
5. Routes
6. A 404 handler for unmatched routes
7. The error-handling middleware, last
In the snippets below, `verifyToken`, `ordersRouter`, `orders`, `HttpError` and `logger` stand for project modules.
```ts
import express, { type ErrorRequestHandler, type RequestHandler } from 'express';
export const requireAuth: RequestHandler = (req, res, next) => {
const token = req.get('authorization')?.replace(/^Bearer /, '');
if (!token) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
res.locals.userId = verifyToken(token); // throws on an invalid token
next();
};
export function createApp() {
const app = express();
app.use(express.json({ limit: '100kb' }));
app.use('/api/orders', requireAuth, ordersRouter);
app.use((req, res) => {
res.status(404).json({ error: 'Not found' });
});
app.use(errorHandler);
return app;
}
```
## Async errors (Express 5)
- In Express 5, a route handler or middleware that returns a rejected promise, or throws inside an `async` function, is forwarded to the error handler automatically. Do not wrap every handler in `try/catch` just to call `next(err)`.
- A promise you start but do not `await` or return is not tracked; `await` it or attach `.catch(next)`.
- Errors thrown inside callbacks (timers, event emitters) are not caught by Express; convert them to promises or call `next(err)` yourself.
```ts
ordersRouter.get('/:id', async (req, res) => {
const order = await orders.find(req.params.id); // rejection goes to errorHandler
if (!order) {
res.status(404).json({ error: 'Order not found' });
return;
}
res.json(order);
});
```
## Error-handling middleware
- Declare it with four parameters `(err, req, res, next)`; Express recognizes error handlers by arity.
- Map known error types to status codes; log unexpected errors with the request ID and return a generic message.
- If headers were already sent, delegate to Express with `next(err)`.
```ts
export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
if (res.headersSent) {
next(err);
return;
}
const status = err instanceof HttpError ? err.status : 500;
if (status >= 500) logger.error({ err, requestId: res.locals.requestId }, 'request failed');
res.status(status).json({ error: status >= 500 ? 'Internal server error' : err.message });
};
```
## Express 5 changes to watch
- `req.query` is a read-only getter; validate it into a new object instead of reassigning it.
- `req.body` is `undefined` until a body parser has run.
- Path syntax changed: wildcards must be named (`/*splat`), and optional parts use braces (`/:file{.:ext}`).
## Typing
- Type handlers with `RequestHandler` / `ErrorRequestHandler` from `express` (types from `@types/express`), or `RequestHandler<Params, ResBody, ReqBody, Query>` when you need typed params and bodies.
- Validate external input (body, query, params) with a schema library at the route boundary and use the parsed result, not the raw `req` values.
## Verify before finishing
Run these when they are available in the project:
- `npx tsc --noEmit`
- route tests with `supertest`, including: missing auth returns 401, an unmatched route returns 404, a handler that rejects returns 500 from the error handler, and order of middleware is preserved
- `npm run lint`
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.