Passport is the de-facto authentication middleware for Node. Nest wraps it with @nestjs/passport so strategies become injectable providers and guards.
Passport Strategies in Nest
A Passport strategy encapsulates how credentials are obtained and verified. Nest classes extend PassportStrategy(Strategy) and implement validate(), which attaches the returned user to the request.
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'email' });
}
async validate(email: string, password: string) {
const user = await this.authService.validateUser(email, password);
if (!user) throw new UnauthorizedException();
return user;
}
}
Whatever validate() returns becomes request.user for subsequent handlers and guards.
AuthGuard('local') runs the local strategy for username/password login.
AuthGuard('jwt') runs the JWT strategy for bearer tokens.
You can create named subclasses like JwtAuthGuard extends AuthGuard('jwt') for cleaner imports.
Register PassportModule in the AuthModule imports.
Passport Nest Cheatsheet
Key packages and classes.
Piece
Role
@nestjs/passport
Nest integration for Passport
passport-local
Email/password strategy
passport-jwt
Bearer JWT strategy
PassportStrategy(Strategy)
Base class for Nest strategies
AuthGuard('name')
Guard that executes a named strategy
Multiple Strategies in One App
It is common to use local strategy for login and JWT strategy for subsequent API calls. OAuth strategies (Google, GitHub) can be added alongside without replacing existing ones.
Custom AuthGuard Subclasses
Subclassing AuthGuard('jwt') lets you override handleRequest or canActivate for public-route metadata checks while keeping strategy naming centralized.
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
Common Mistakes
Forgetting to register the strategy as a provider in AuthModule.
Mismatching strategy name between PassportStrategy options and AuthGuard('name').
Expecting request.user before any AuthGuard has run.
Putting heavy business logic inside validate() instead of AuthService.
Key Takeaways
Nest Passport strategies implement validate() and populate request.user.
AuthGuard('strategy') executes that strategy for a route.
Local + JWT is a common pair for login and protected APIs.
Strategies are Nest providers and can inject AuthService/ConfigService.
Pro Tip
Create thin guard aliases (LocalAuthGuard, JwtAuthGuard) instead of scattering AuthGuard('jwt') string literals, so renaming a strategy later is a one-file change.
You now understand Passport in Nest. Next, implement JWT authentication end-to-end.