Adding Route Protections with Guards
Learn how to protect routes with guards in NestJS.
We'll cover the following...
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:
This command will create an auth.guard.ts file in the auth folder with the following boilerplate code:
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 ...