April 30, 2026
1 min read
A practical guide to implementing stateless JWT authentication in NestJS using Guards, Passport strategies, and protected routes.
JWT (JSON Web Token) is a compact, stateless authentication mechanism widely used in REST APIs. NestJS makes it straightforward to implement with its built-in Guards and Passport integration.
npm install @nestjs/jwt @nestjs/passport passport passport-jwt
npm install -D @types/passport-jwt
Configure JwtModule with a secret and expiration:
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '7d' },
})
The strategy validates the token and extracts the payload on every protected request:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
});
}
async validate(payload: { sub: string; email: string }) {
return { id: payload.sub, email: payload.email };
}
}
Apply the JwtAuthGuard to any controller or route that requires authentication:
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
NestJS + JWT provides a clean, decorator-driven authentication layer that scales well across large APIs.