0
0
NestJSframework~5 mins

Why guards control access in NestJS

Choose your learning style9 modes available
Introduction

Guards help decide who can use parts of your app. They keep things safe by checking if someone is allowed before they get in.

When you want only logged-in users to see certain pages.
When you need to check if a user has special rights before doing an action.
When you want to block access to parts of your app for some users.
When you want to check a password or token before allowing access.
When you want to protect routes from unauthorized users.
Syntax
NestJS
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class MyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    // Your logic here
    return true; // or false
  }
}

The canActivate method decides if access is allowed.

Return true to allow, false to block.

Examples
This guard allows access only if the user is logged in.
NestJS
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return !!request.user; // allow if user exists
  }
}
This guard checks if the user has a specific role before allowing access.
NestJS
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private readonly role: string) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return request.user?.role === this.role;
  }
}
Sample Program

This example shows a guard that only lets requests with ?allow=true access the route. Others are blocked.

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

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

@Controller('test')
export class TestController {
  @Get()
  @UseGuards(SimpleGuard)
  getData() {
    return 'Access granted';
  }
}
OutputSuccess
Important Notes

Guards run before your route handler to protect it.

They can check anything: user info, tokens, request data.

Always return true or false to control access.

Summary

Guards control who can use parts of your app by allowing or blocking access.

They check conditions like login status or user roles before routes run.

Use guards to keep your app safe and organized.