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? 👇



















