0
0
NestJSframework~5 mins

Combining multiple guards in NestJS

Choose your learning style9 modes available
Introduction

Guards help protect parts of your app by checking if a user can access them. Combining multiple guards lets you add more than one check easily.

When you want to check if a user is logged in <strong>and</strong> has a specific role before accessing a page.
When you need to verify a user's token <strong>and</strong> confirm their account is active.
When you want to apply different security checks together, like rate limiting <strong>and</strong> permission checks.
When you want to reuse small guard checks and combine them for bigger rules.
Syntax
NestJS
import { UseGuards } from '@nestjs/common';

@UseGuards(FirstGuard, SecondGuard)
export class SomeController {
  // your routes here
}

You list multiple guards inside @UseGuards() separated by commas.

All guards must return true for access to be allowed.

Examples
This example protects the ProfileController with two guards: one for authentication and one for roles.
NestJS
import { UseGuards, Controller, Get } from '@nestjs/common';
import { AuthGuard } from './auth.guard';
import { RolesGuard } from './roles.guard';

@Controller('profile')
@UseGuards(AuthGuard, RolesGuard)
export class ProfileController {
  @Get()
  getProfile() {
    return 'User profile data';
  }
}
Here, two guards protect only the getDashboard route, checking JWT and if the user is active.
NestJS
import { UseGuards, Get, Controller } from '@nestjs/common';
import { JwtGuard } from './jwt.guard';
import { ActiveUserGuard } from './active-user.guard';

@Controller('dashboard')
export class DashboardController {
  @Get()
  @UseGuards(JwtGuard, ActiveUserGuard)
  getDashboard() {
    return 'Dashboard content';
  }
}
Sample Program

This example shows a controller protected by two guards. Both must allow access for the route to work.

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

@Injectable()
class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    // Simulate user is authenticated
    return true;
  }
}

@Injectable()
class RoleGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    // Simulate user has role
    return true;
  }
}

@Controller('secure')
@UseGuards(AuthGuard, RoleGuard)
export class SecureController {
  @Get()
  getSecureData() {
    return 'Access granted to secure data';
  }
}
OutputSuccess
Important Notes

Guards run in the order you list them inside @UseGuards().

If any guard returns false, access is denied immediately.

You can apply guards at the controller level or on individual routes.

Summary

Use @UseGuards() with multiple guards separated by commas to combine checks.

All guards must approve access for the user to proceed.

Combining guards helps keep your code clean and reusable.