Middleware runs before handlers so it can inspect, modify, or validate the request. This ensures handlers get the right data or that unauthorized requests are blocked early.
export function addUserId(req, res, next) {
req.userId = 42;
next();
}
// Route handler
@Get('profile')
getProfile(@Req() req) {
return req.userId;
}Middleware runs first and can add or change properties on the request object. The handler then accesses these properties as part of the same request.
Middleware runs first (1), can modify request or response (4), then the route handler runs (2), and finally the response is sent (3).
In NestJS, middleware is applied using app.use(path, middleware). Other options are invalid methods.
export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(loggingMiddleware) .forRoutes('users'); } } @Get('/users') getUsers() { return ['Alice', 'Bob']; }
Middleware paths must match routes exactly including the leading slash. 'users' does not match '/users', so middleware is skipped.
