0
0
NestJSframework~30 mins

Combining multiple guards in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Combining Multiple Guards in NestJS
📖 Scenario: You are building a simple NestJS API that needs to protect a route with two guards: one to check if the user is authenticated, and another to check if the user has admin rights.This is like having two security guards at a door: one checks your ID, the other checks if you have a special pass.
🎯 Goal: Create a NestJS controller with a route protected by two guards combined using the @UseGuards() decorator.The route should only be accessible if both guards allow access.
📋 What You'll Learn
Create two guard classes: AuthGuard and AdminGuard
Create a controller called AppController with a route GET /protected
Apply both guards together on the /protected route using @UseGuards()
The guards should implement the CanActivate interface and return true or false accordingly
💡 Why This Matters
🌍 Real World
Combining multiple guards is common in real NestJS apps to layer security checks, like authentication and authorization.
💼 Career
Understanding how to combine guards helps you build secure APIs and is a key skill for backend developers working with NestJS.
Progress0 / 4 steps
1
Create the two guard classes
Create two guard classes called AuthGuard and AdminGuard. Each should implement the CanActivate interface from @nestjs/common and have a canActivate() method that returns true.
NestJS
Need a hint?

Remember to import CanActivate and ExecutionContext from @nestjs/common.

2
Create the controller with a protected route
Create a controller class called AppController with a method getProtected() decorated with @Get('protected') from @nestjs/common. The method should return the string 'Protected content'.
NestJS
Need a hint?

Import Controller and Get from @nestjs/common and decorate the class and method properly.

3
Apply both guards to the protected route
Use the @UseGuards() decorator from @nestjs/common on the getProtected() method. Pass both AuthGuard and AdminGuard inside @UseGuards() to combine them.
NestJS
Need a hint?

Import UseGuards and add @UseGuards(AuthGuard, AdminGuard) above the getProtected() method.

4
Export the controller and guards for use
Add export keywords to the AppController, AuthGuard, and AdminGuard classes so they can be used in other parts of the application.
NestJS
Need a hint?

Make sure all classes have the export keyword before class.