0
0
NestjsConceptBeginner · 3 min read

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.

typescript
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' };
  }
}
Output
If request header 'x-api-key' equals 'secret123', response: { message: 'Access granted to protected data' } Otherwise, response: 403 Forbidden error
🎯

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 true to allow or false to 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.

Key Takeaways

Guards in NestJS control access to routes by allowing or denying requests before they reach handlers.
Implement guards by creating a class with a canActivate method that returns true or false.
Use guards for authentication, authorization, and custom access rules.
Apply guards with the @UseGuards() decorator on controllers or specific routes.
Guards help protect your app by stopping unauthorized requests early.