PassportStrategy

Base class for defining Passport authentication strategies as injectable providers.

Since NestJS 10/11 Spec ↗

Syntax

class X extends PassportStrategy(Strategy, name?)

Parameters

NameTypeRequiredDescription
Strategy Function No The underlying passport strategy constructor.
name string No Optional strategy name used by AuthGuard.

Returns

Class — A class to extend with a validate() method.

Throws

  • UnauthorizedException — Returned when validate resolves null/false.

Examples

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.JWT_SECRET!,
    });
  }
  validate(payload: { sub: string }) {
    return { userId: payload.sub };
  }
}

Notes

Install @nestjs/passport, passport, and the strategy package. The value returned from validate() is attached to request.user. Protect routes with @UseGuards(AuthGuard('jwt')).