Skip to content

Guards in Nest.js

Guards have a single responsibility. They determine whether a given request will be handled by the route handler or not, depending on certain conditions (like permissions, roles, ACLs, etc.) present at run-time. This is often referred to as authorization.

auth.guard
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
// return true or false based on your condition
return true;
}
}

Binding guards

Guards can apply globally or to specific controllers or routes. To apply it to a controller or route, use the @UseGuards() decorator. This decorator may take a single argument, or a comma-separated list of arguments.

controller-scoped
protected.controller.ts
import { Controller, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';
@Controller('protected')
@UseGuards(AuthGuard)
export class ProtectedController {
...
}
method-scoped
protected.controller.ts
import { Controller, Get, UseGuards } from "@nestjs/common";
import { AuthGuard } from "./auth.guard";
@Controller("protected")
export class ProtectedController {
@Get()
@UseGuards(AuthGuard)
getProtectedData() {
return "this route is protected by AuthGuard";
}
}
global-scoped
app.module.ts
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from './auth.guard';
@Module({
providers: [
{
provide: APP_GUARD,
useClass: AuthGuard,
},
],
})
export class AppModule {}