What is Guard in NestJS: Explanation and Example
Guard in NestJS is a special class that controls whether a request can proceed to a route handler based on custom logic. It acts like a gatekeeper, deciding if the request should be allowed or denied before reaching the controller.How It Works
Think of a Guard as a security guard at the entrance of a building. Before letting anyone inside, the guard checks if they have permission. In NestJS, guards check requests before they reach your route handlers.
When a request comes in, NestJS runs the guard's logic. If the guard says "yes," the request continues. If it says "no," NestJS stops the request and returns an error, like 403 Forbidden.
This helps you protect routes by adding rules like "only logged-in users can access this" or "only admins can delete data." Guards run before any other code in the route.
Example
This example shows a simple guard that allows access only if a request has a header x-api-key with a specific value.
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; import { Observable } from 'rxjs'; @Injectable() export class ApiKeyGuard implements CanActivate { canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> { const request = context.switchToHttp().getRequest(); const apiKey = request.headers['x-api-key']; return apiKey === 'secret123'; } } // Usage in a controller import { Controller, Get, UseGuards } from '@nestjs/common'; @Controller('data') export class DataController { @Get() @UseGuards(ApiKeyGuard) getData() { return { message: 'Access granted to protected data' }; } }
When to Use
Use guards when you want to control access to routes based on conditions like authentication, roles, or custom rules. For example:
- Only logged-in users can access certain pages.
- Only users with admin rights can delete or update data.
- Requests must have a valid API key or token.
Guards help keep your app safe by stopping unauthorized requests early.
Key Points
- Guards run before route handlers to allow or block requests.
- They return
trueto allow orfalseto deny access. - Commonly used for authentication and authorization.
- Implemented by creating a class that implements
CanActivate. - Applied using the
@UseGuards()decorator on controllers or routes.