Overview

Protect routes with JWT authentication. Supports public route bypass and detailed error messages.

Features

  • Passport integration
  • Public route support
  • Token expiration handling
  • Optional auth routes

Installation

npx hanma add jwt-auth-guard --framework nest

Dependencies

@nestjs/passport, passport-jwt, jsonwebtoken

Code

import {
  Injectable,
  ExecutionContext,
  UnauthorizedException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { AuthGuard } from "@nestjs/passport";
import { IS_PUBLIC_KEY } from "../decorators/public.decorator";

@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {
  constructor(private reflector: Reflector) {
    super();
  }

  canActivate(context: ExecutionContext) {
    // Check if route is marked as public
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) {
      return true;
    }

    return super.canActivate(context);
  }

  handleRequest<TUser = any>(
    err: any,
    user: TUser,
    info: any,
    context: ExecutionContext
  ): TUser {
    // Check for public routes that optionally accept authentication
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (err || !user) {
      if (isPublic) {
        return null as TUser;
      }

      if (info?.name === "TokenExpiredError") {
        throw new UnauthorizedException("Token has expired");
      }
      if (info?.name === "JsonWebTokenError") {
        throw new UnauthorizedException("Invalid token");
      }
      throw new UnauthorizedException("Authentication required");
    }

    return user;
  }
}

Usage

@UseGuards(JwtAuthGuard)
@Get('protected')
protectedRoute() {}

Dependencies

Frequently Asked Questions

How do I install JWT Auth Guard?
Run the following command: npx hanma add jwt-auth-guard --framework nest
What dependencies are required?
This snippet requires: @nestjs/passport, passport-jwt, jsonwebtoken. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to src/guards/jwt-auth.guard.ts.
Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.