0
0
NestJSframework~5 mins

JWT authentication guard in NestJS

Choose your learning style9 modes available
Introduction

A JWT authentication guard helps protect parts of your app by checking if a user has a valid token before allowing access.

When you want to secure routes so only logged-in users can access them.
When you need to verify user identity using tokens sent with requests.
When building APIs that require user authentication without sessions.
When you want to protect sensitive data or actions in your backend.
When you want to easily check user permissions based on token info.
Syntax
NestJS
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);
    if (!token) return false;

    try {
      const payload = this.jwtService.verify(token);
      request.user = payload;
      return true;
    } catch {
      return false;
    }
  }

  private extractTokenFromHeader(request: any): string | null {
    const authHeader = request.headers['authorization'];
    if (!authHeader) return null;
    const [type, token] = authHeader.split(' ');
    return type === 'Bearer' ? token : null;
  }
}

The guard implements CanActivate to decide if a request can continue.

It extracts the JWT from the Authorization header and verifies it.

Examples
This example shows the main method that checks the token and allows or denies access.
NestJS
canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  const token = this.extractTokenFromHeader(request);
  if (!token) return false;

  try {
    const payload = this.jwtService.verify(token);
    request.user = payload;
    return true;
  } catch {
    return false;
  }
}
This helper method gets the token from the header if it starts with 'Bearer'.
NestJS
private extractTokenFromHeader(request: any): string | null {
  const authHeader = request.headers['authorization'];
  if (!authHeader) return null;
  const [type, token] = authHeader.split(' ');
  return type === 'Bearer' ? token : null;
}
Sample Program

This example shows a simple controller with a route protected by the JWT guard. Only requests with a valid JWT can access the profile data.

NestJS
import { Controller, Get, UseGuards, Req } from '@nestjs/common';
import { JwtAuthGuard } from './jwt-auth.guard';

@Controller('profile')
export class ProfileController {
  @UseGuards(JwtAuthGuard)
  @Get()
  getProfile(@Req() request: any) {
    return { message: 'User profile data', user: request.user };
  }
}

// JwtAuthGuard code as shown in syntax section
OutputSuccess
Important Notes

Always send the JWT in the Authorization header as Bearer <token>.

Make sure to handle token expiration and errors gracefully in your app.

Use HTTPS to keep tokens safe during transmission.

Summary

JWT authentication guards protect routes by verifying tokens.

They check the Authorization header for a valid Bearer token.

When valid, the guard allows access and attaches user info to the request.