Guards help decide if a request can continue or not. They protect parts of your app by checking rules before running code.
0
0
Guard interface (canActivate) in NestJS
Introduction
When you want to check if a user is logged in before showing a page.
When you need to verify user roles before allowing access to certain features.
When you want to block requests that don't meet certain conditions.
When you want to add simple security checks to your routes.
When you want to control access to APIs based on custom logic.
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 returns true to allow or false to block the request.
You can return a boolean, a Promise, or an Observable for async checks.
Examples
Checks if the request has an 'x-api-key' header and allows access only if it exists.
NestJS
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return !!request.headers['x-api-key'];
}Asynchronously checks if the user is active before allowing access.
NestJS
async canActivate(context: ExecutionContext): Promise<boolean> { const user = await this.authService.getUserFromRequest(context.switchToHttp().getRequest()); return user?.isActive ?? false; }
Sample Program
This example creates a guard that checks if the request has an 'authorization' header. If yes, it allows access to the profile route; otherwise, it blocks it.
NestJS
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import { Controller, Get, UseGuards } from '@nestjs/common'; @Injectable() class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); // Simple check: allow if 'authorization' header exists return Boolean(request.headers['authorization']); } } @Controller('profile') @UseGuards(AuthGuard) export class ProfileController { @Get() getProfile() { return { message: 'Access granted to profile' }; } }
OutputSuccess
Important Notes
Guards run before any route handler and can stop the request early.
Use @UseGuards() to apply guards to controllers or routes.
Guards can be combined to check multiple conditions.
Summary
Guards control access by returning true (allow) or false (deny).
Implement the canActivate method to add your logic.
Use guards to protect routes and add security checks easily.