Junior — Middle
Can you explain the mechanism of the handler chain operation in NestJS?
sobes.tech AI
Answer from AI
In NestJS, the chain of handlers is implemented through middleware, guards, interceptors, and pipes, which sequentially process incoming requests. Each of these components can perform its own task — for example, middleware can log requests, guards can check authorization, pipes can validate and transform data, and interceptors can modify the behavior of methods or results.
The mechanism is similar to a chain of responsibilities: the request passes through a sequence of handlers, each of which can either pass control further or terminate execution.
Example of middleware in NestJS:
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: Function) {
console.log(`Request... ${req.method} ${req.url}`);
next();
}
}
This middleware is called in the chain and, after its work, calls next() to pass control to the next handler.