0
0
NestJSframework~30 mins

Protected routes with guards in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Protected routes with guards
📖 Scenario: You are building a simple NestJS API that has some routes only accessible to logged-in users. You want to protect these routes using guards.
🎯 Goal: Create a NestJS guard to protect a route so only authorized users can access it.
📋 What You'll Learn
Create a basic NestJS controller with one public route and one protected route
Create a guard class that implements CanActivate
Use the guard to protect the protected route
Return true from the guard to allow access
💡 Why This Matters
🌍 Real World
Protecting routes in a web API to ensure only authorized users can access sensitive data or actions.
💼 Career
Understanding guards is essential for backend developers working with NestJS to implement security and access control.
Progress0 / 4 steps
1
Create a controller with two routes
Create a NestJS controller class called AppController with two routes: a GET route at /public that returns the string 'This is public', and a GET route at /protected that returns the string 'This is protected'.
NestJS
Need a hint?

Use @Controller() to define the controller and @Get() decorators for routes.

2
Create a guard class implementing CanActivate
Create a guard class called AuthGuard that implements the CanActivate interface from @nestjs/common. Inside the canActivate method, return true to allow access.
NestJS
Need a hint?

Import CanActivate and ExecutionContext from @nestjs/common. Implement canActivate method returning true.

3
Apply the guard to the protected route
Import UseGuards from @nestjs/common and apply the AuthGuard to the /protected route using the @UseGuards(AuthGuard) decorator.
NestJS
Need a hint?

Use the @UseGuards(AuthGuard) decorator just above the @Get('protected') route.

4
Export the guard and controller for use
Add export keyword before the AppController class declaration to export it. Ensure the AuthGuard class is also exported.
NestJS
Need a hint?

Make sure both AppController and AuthGuard have the export keyword.