Protected routes keep parts of your app safe by checking who can access them. Guards help decide if a user is allowed or not before showing the page.
0
0
Protected routes with guards in NestJS
Introduction
When you want only logged-in users to see certain pages.
When you need to check user roles before allowing access.
When you want to block unauthorized users from API endpoints.
When you want to add extra checks before running route handlers.
Syntax
NestJS
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import { Observable } from 'rxjs'; @Injectable() export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> { // Your logic here return true; // or false } }
The guard class must implement CanActivate interface.
The canActivate method returns true to allow access, false to block.
Examples
This guard checks if the request has an authorization header to allow access.
NestJS
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; @Injectable() export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); return !!request.headers.authorization; } }
This guard allows access only if the user has the 'admin' role.
NestJS
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; @Injectable() export class RolesGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); const user = request.user; return user?.role === 'admin'; } }
Apply the guard to protect the 'profile' route so only authorized users can access it.
NestJS
@UseGuards(AuthGuard) @Get('profile') getProfile() { return 'User profile data'; }
Sample Program
This example shows a simple guard that checks for an authorization header. The 'profile' route is protected and only accessible if the header is present.
NestJS
import { Controller, Get, UseGuards, Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; @Injectable() class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); // Simple check: allow if header 'authorization' exists return !!request.headers.authorization; } } @Controller('users') export class UserController { @UseGuards(AuthGuard) @Get('profile') getProfile() { return { message: 'This is a protected user profile' }; } }
OutputSuccess
Important Notes
Guards run before route handlers to decide access.
You can combine multiple guards using @UseGuards() with several classes.
Always test your guards to avoid accidentally blocking all users.
Summary
Guards protect routes by allowing or blocking access.
Implement CanActivate and use canActivate to add your logic.
Apply guards with @UseGuards() on controllers or routes.