Skip to main content

Guards

Guard list

GuardDescription
AuthGuardProtects HTTP routes by validating Authorization: Bearer <token> and attaching the decoded payload to the request.

AuthGuard is provided by nestjs-auth-module to protect HTTP routes that require authentication.

How it works

  • Reads the Authorization header in the form: Bearer <token>
  • Decodes the token using the active provider (AuthService.decodeAsync)
  • Attaches the decoded payload to request.tokenPayload
  • Throws UnauthorizedException if the token is missing/invalid/expired

Usage

Protect a controller or route

example.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from 'nestjs-auth-module';

@Controller('example')
@UseGuards(AuthGuard)
export class ExampleController {
@Get('private')
privateRoute() {
return { ok: true };
}
}

Protect a single endpoint only

example.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from 'nestjs-auth-module';

@Controller('example')
export class ExampleController {
@Get('private')
@UseGuards(AuthGuard)
privateRoute() {
return { ok: true };
}

@Get('public')
publicRoute() {
return { ok: true };
}
}
note

AuthGuard stores the decoded payload at request.tokenPayload. Use the decorators documented in the next section to access it cleanly.