DEV Community

Cover image for The Journey of a Request Through NestJS
Rafael
Rafael

Posted on

The Journey of a Request Through NestJS

Imagine that our application holds one of the greatest secrets of the universe. Naturally, a secret of such importance must be very well protected.

Before anyone can access it, an HTTP request must go through several layers of verification, validation, and processing.

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>
Enter fullscreen mode Exit fullscreen mode

Middleware: The First Encounter

Before anything else, we want to know that someone is trying to access our secret.

Middleware is the first application-level component our request encounters. It has access to the request and response objects and can execute logic before passing control to the next component.

use(req: Request, res: Response, next: NextFunction) {
  console.log(`${req.method} ${req.url}`);
  next();
}
Enter fullscreen mode Exit fullscreen mode

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 determine whether a request is allowed to proceed. Unlike middleware, they have access to the ExecutionContext, which provides information about the controller and handler that will be executed.

canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();

  return this.authService.canAccessSecrets(request);
}
Enter fullscreen mode Exit fullscreen mode

If access is denied, the request's journey ends here.

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 execute logic both before and after the handler execution, making them particularly 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`);
    }),
  );
}
Enter fullscreen mode Exit fullscreen mode

For now, we have only started the clock. We will come back to it later.

Pipe: Making Sure Things Make Sense

Even the greatest secrets deserve properly validated input.

Pipes validate and transform the arguments passed to a route handler. In our case, the secret identifier must be an integer.

@Param('id', ParseIntPipe) id: number
Enter fullscreen mode Exit fullscreen mode

The identifier, originally received as the string "1", is now the number 1.

Had it been something other than a valid integer, our journey would have ended with a BadRequestException.

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);
}
Enter fullscreen mode Exit fullscreen mode

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 the downstream execution. When multiple interceptors are involved, the response travels through them in reverse order, following a first-in, last-out pattern.

This is where we can transform the result, collect metrics, or perform additional operations.

In our example, the finalize operator records the 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 allow us to customize how they are translated into HTTP responses.

Unlike the other components, exception filters are not part of the successful execution path. They come into play when something goes wrong.

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
Enter fullscreen mode Exit fullscreen mode
{
  "answer": 42
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)