NestJS Authentication in 5 Minutes π
Authentication in NestJS sounds complicated at firstβ¦
But the actual flow is surprisingly simple π
User Login
β
Verify Credentials
β
Generate JWT Token
β
Protected Routes
β
Validate Token
1οΈβ£ Install required packages
npm install @nestjs/jwt @nestjs/passport passport passport-jwt bcrypt
npm install -D @types/passport-jwt
2οΈβ£ Generate auth files
nest g module auth
nest g service auth
nest g controller auth
3οΈβ£ Configure JWT (auth.module.ts)
@Module({
imports: [
JwtModule.register({
secret: "super-secret-key",
signOptions: {
expiresIn: "1d",
},
}),
],
})
export class AuthModule {}
4οΈβ£ Create login function (auth.service.ts)
@Injectable()
export class AuthService {
constructor(
private jwtService: JwtService,
) {}
async login(user: any) {
const payload = {
id: user.id,
email: user.email,
};
return {
access_token:
this.jwtService.sign(payload),
};
}
}
5οΈβ£ Protect routes with JWT
@UseGuards(AuthGuard("jwt"))
@get("profile")
getProfile(@Request() req) {
return req.user;
}
Authentication = Login β Token β Verify β Access π₯
β οΈ Bonus tip: Never store passwords directly. Use:
bcrypt.hash()
bcrypt.compare()
What confused you most when learning authentication? π
Top comments (0)