Imagine that our application holds one of the greatest secrets in the universe. Naturally, such a secret must be very well protected.
Before the route handler can return it, an HTTP request may pass through layers responsible for verification, validation, and processing. In a configured NestJS route, the successful path goes through middleware, guards, interceptors, and pipes before reaching the handler, then returns through the interceptors. Uncaught errors take a separate path to exception filters.
This gives us a perfect opportunity to explore the NestJS request lifecycle.
Our journey begins with a seemingly ordinary HTTP request:
GET /secrets/1
Authorization: Bearer <token>Middleware: The First Encounter
Before anything else, we want to know that someone is trying to access our secret.
Middleware is the first Nest application component in this HTTP path. It receives the request and response objects and can run logic before passing control to the next middleware or to Nest’s routing process.
use(req: Request, res: Response, next: NextFunction) {
console.log(`${req.method} ${req.url}`);
next();
}We now know someone is looking for the secret. Whether they should be allowed to find it is another matter.
Guard: Permission to Proceed
Not everyone should have access to the secrets of the universe.
Guards decide whether a request may proceed to its handler. Unlike middleware, they receive an ExecutionContext, which includes information about the controller and handler that Nest selected for the request.
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return this.authService.canAccessSecrets(request);
}If the guard returns false, Nest denies access and skips the handler. The resulting ForbiddenException is handled on the exception path. Fortunately, our requester is authorized.
Interceptor: Keeping an Eye on Things
Given the importance of our secret, we might want to know how long it takes to retrieve it.
Interceptors can run logic before and after the handler. This makes them useful for cross-cutting concerns such as logging, monitoring, and response transformation.
intercept(context: ExecutionContext, next: CallHandler) {
const start = Date.now();
return next.handle().pipe(
finalize(() => {
console.log(`Elapsed: ${Date.now() - start}ms`);
}),
);
}For now, we have only started the clock. We will come back to it later. The finalize operator runs when the returned Observable terminates, whether it completes or errors.
Pipe: Making Sure Things Make Sense
Even the greatest secrets deserve properly validated input.
Pipes validate or transform the arguments passed to a route handler. In our case, the secret identifier arrives as text but the handler needs an integer.
@Param('id', ParseIntPipe) id: numberThe identifier, originally received as the string "1", is now the number 1.
If the value cannot be converted, ParseIntPipe throws a BadRequestException. The handler is skipped, and Nest sends the error through its exception handling layer.
Controller and Service: Reaching the Destination
After successfully passing through the previous layers, our request finally reaches the controller.
The controller handles the incoming request and delegates the business logic to the service.
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.secretsService.findOne(id);
}The secret has finally been retrieved.
However, our journey is not quite over.
Interceptor: The Way Back
Remember the clock we started earlier?
Interceptors wrap downstream execution. When multiple interceptors are involved, the response travels back through them in reverse order, following a first-in, last-out pattern. An interceptor applied globally runs before controller- and route-level interceptors on the way in, and after them on the way out.
This is where we can transform the result, collect metrics, or perform additional operations. In our example, finalize records elapsed time when the Observable terminates.
Exception Filter: When Things Go Wrong
Of course, not every journey goes according to plan.
Access might be denied, an identifier might be invalid, or the service responsible for storing our secret might fail.
Exception filters handle uncaught exceptions and let us customize how they become HTTP responses. A guard denial, a pipe error, or a failure in the handler can skip the remaining successful path and reach an applicable filter.
Unlike the other components, exception filters do not run on a successful request. They come into play only when something goes wrong and the exception is not handled by application code.
Fortunately, nothing went wrong this time.
The Answer
After passing through multiple layers of protection, validation, transformation, and processing, our request finally receives its response.
HTTP/1.1 200 OK
Content-Type: application/json{
"answer": 42
}All that infrastructure for a single number.
Now that we have the answer, we just need to figure out the question.
Further reading: NestJS — Request Lifecycle
Also published on DEV: The Journey of a Request Through NestJS
