JWT Authentication
Issue signed JSON Web Tokens on login and validate them on protected routes.
Syntax
this.jwtService.sign(payload)JWT (JSON Web Token) is the standard way to authenticate stateless APIs. On login you sign a token; the client sends it back on every request.
The two halves
- Sign - after checking credentials,
JwtService.sign()creates a token holding the user id. - Verify - a JWT strategy validates the token on incoming requests and populates
request.user.
Configure the secret and expiry via JwtModule.register().
Example
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(private jwt: JwtService) {}
async login(user: { id: number; username: string }) {
const payload = { sub: user.id, username: user.username };
return { access_token: this.jwt.sign(payload) };
}
}When to use it
- A developer calls JwtService.sign({ sub: user.id }) after validating credentials so the login endpoint returns a short-lived access token.
- A team configures JwtModule.registerAsync() to load the secret from ConfigService so the JWT secret is never committed to source code.
- An engineer sets the token expiry to 15 minutes and issues a separate refresh token, using the short expiry to limit exposure of stolen access tokens.
More examples
Install JWT packages
Installs the NestJS JWT module and passport-jwt strategy along with its TypeScript type definitions.
npm install @nestjs/jwt passport-jwt
npm install -D @types/passport-jwtJwtModule setup and token signing
Registers JwtModule with a secret and expiry, then uses JwtService.sign() in the login method to issue a signed access token.
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
@Module({
imports: [
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '15m' },
}),
],
providers: [AuthService],
})
export class AuthModule {}
// In AuthService.login():
login(user: User) {
return { access_token: this.jwtService.sign({ sub: user.id, email: user.email }) };
}JWT strategy for validation
Implements JwtStrategy to extract the Bearer token, verify its signature, and return the decoded payload as the request user object.
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: number; email: string }) {
return { userId: payload.sub, email: payload.email };
}
}
Discussion