0
0
NestJSframework~5 mins

Guard binding levels in NestJS

Choose your learning style9 modes available
Introduction

Guards control who can access parts of your app. Binding levels decide where guards apply: globally, to a whole controller, or just one route.

You want to check user permissions for the entire app.
You want to protect all routes in a specific controller.
You want to secure only one specific route.
You want different guards for different parts of your app.
You want to reuse guards easily without repeating code.
Syntax
NestJS
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class MyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    // your logic here
    return true;
  }
}

// Global binding
app.useGlobalGuards(new MyGuard());

// Controller binding
@UseGuards(MyGuard)
@Controller('cats')
export class CatsController {}

// Route binding
@UseGuards(MyGuard)
@Get()
findAll() {}

Global guards run for every request in the app.

Controller guards run for all routes inside that controller.

Examples
This applies the guard to every route in the app.
NestJS
// Global guard binding
app.useGlobalGuards(new MyGuard());
This applies the guard to all routes inside the UsersController.
NestJS
@UseGuards(MyGuard)
@Controller('users')
export class UsersController {}
This applies the guard only to the getProfile route.
NestJS
@UseGuards(MyGuard)
@Get('profile')
getProfile() {}
Sample Program

This example shows a guard applied at the controller level. It only allows access if the URL query has ?allow=true. Both routes in HelloController are protected by this guard.

NestJS
import { Controller, Get, Injectable, CanActivate, ExecutionContext, UseGuards } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { Module } from '@nestjs/common';

@Injectable()
class SimpleGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    // Allow only if query param 'allow' is 'true'
    return request.query.allow === 'true';
  }
}

@Controller('hello')
@UseGuards(SimpleGuard) // Controller level guard
class HelloController {
  @Get()
  sayHello() {
    return 'Hello World';
  }

  @Get('open')
  openRoute() {
    return 'Open Route';
  }
}

@Module({
  controllers: [HelloController],
  providers: [SimpleGuard],
})
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}

bootstrap();
OutputSuccess
Important Notes

Guards run before route handlers to decide if the request can continue.

Use global guards for app-wide rules like authentication.

Use controller or route guards for more specific access control.

Summary

Guards can be bound globally, to controllers, or to individual routes.

Global guards protect every request in the app.

Controller and route guards let you control access more precisely.