Middleware Guide
This skill explains how to structure and apply Express middleware safely and consistently.
Types of middleware
- •Auth: authenticates identity and attaches it to the request context
- •Authorization: enforces permissions/roles
- •Validation: validates input and short-circuits on invalid requests
- •Context: attaches correlation ids, request metadata, and logging context
- •Error boundary: catches errors and converts them into consistent responses
Recommended structure
text
src/middleware/ auth.ts authorization.ts request_context.ts validation.ts error_boundary.ts
Error boundary pattern
Ensure async errors are captured:
ts
export function asyncHandler(fn) {
return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}
Register error middleware last:
ts
app.use("/api", routes);
app.use(errorBoundary); // last
Related Skills
- •
architecture-overview - •
async-and-errors