Middleware is a function or class that runs before the route handler. It gets the request and response objects and a next() function. It can read or change the request and the response, end the response early, or call next() to pass control on. If it neither ends the response nor calls next(), the request is left hanging.
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(`${req.method} ${req.url}`);
next();
}
}
// Apply in module
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes('users');
}
}
A class middleware implements NestMiddleware and its use() function. To apply it, the module implements NestModule and registers it in configure() through the MiddlewareConsumer. forRoutes() takes a path, a controller class, or a route object with a path and an HTTP method. exclude() skips routes.
Nest middleware works like Express middleware by default, so most Express middleware packages work in Nest too.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓