Middleware
Last updated 2026-10-07
Rhea.js installs this fixed order:
- Request ID (
X-Request-ID) - Request logging
- Helmet security headers
- CORS (only when origins are configured)
- Rate limiting (disabled in the
testenvironment unless configured) - Request timeout
- JSON body parser with size limit
- Prototype-pollution guard
- Your routes and plugins
- 404 handler, then error handler
Write your own middleware as normal Express middleware and generate a stub with rhea generate middleware auth.
import { UnauthorizedError, type NextFunction, type Request, type Response } from "@rheajs/core";
export function requireApiKey(expected: string) {
return (req: Request, _res: Response, next: NextFunction) => {
if (req.header("x-api-key") !== expected) return next(new UnauthorizedError("Invalid API key"));
next();
};
}To add middleware globally from a plugin use ctx.addMiddleware. See Plugins.