Search⌘ K

Adding Route Protections with Guards

Explore how to implement route protection in NestJS by creating and applying guards that validate JWT tokens. You'll learn to restrict access to endpoints, handle token verification, and manage unauthorized requests effectively.

In our virtual library, the /books endpoint is reserved for authenticated users only. In this lesson, we will use a NestJS guard to enforce this restriction by validating JWT tokens attached to incoming requests.

Generating AuthGuard

To generate AuthGuard, run the nest g guard auth --no-spec command in the terminal below:

Terminal 1
Terminal
Loading...

This command will create an auth.guard.ts file in the auth folder with the following boilerplate code:

TypeScript 4.9.5
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
return true;
}
}

The AuthGuard class implements the CanActivate interface, necessitating a canActivate() method. The canActivate() method receives an ExecutionContext object as a parameter, which holds details about the current request cycle.

The return value expected by the canActivate method is a boolean. It can return this value (boolean) synchronously or asynchronously: Promise<boolean> or (Observable<boolean>).

In the current implementation, the canActivate() method allows all requests by ...