Passport.js helps you add login and user verification easily. It works with NestJS to keep your app safe.
Passport.js integration in NestJS
import { PassportModule } from '@nestjs/passport'; @Module({ imports: [PassportModule.register({ defaultStrategy: 'local' })], providers: [AuthService, LocalStrategy], controllers: [AuthController], }) export class AuthModule {}
Use PassportModule.register() to set default login strategy.
Provide strategy classes like LocalStrategy to define how login works.
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-local'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super(); } async validate(username: string, password: string): Promise<any> { const user = await this.authService.validateUser(username, password); if (!user) { throw new UnauthorizedException(); } return user; } }
import { Controller, Post, UseGuards, Request } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller('auth') export class AuthController { @UseGuards(AuthGuard('local')) @Post('login') async login(@Request() req) { return req.user; } }
This example shows a simple NestJS module using Passport.js local strategy. It checks username and password from a fixed list and returns the user if valid. The login route is protected and returns user info on success.
import { Module, Injectable, Controller, Post, UseGuards, Request } from '@nestjs/common'; import { PassportModule } from '@nestjs/passport'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-local'; import { AuthGuard } from '@nestjs/passport'; import { UnauthorizedException } from '@nestjs/common'; @Injectable() class AuthService { private users = [{ username: 'john', password: 'changeme' }]; async validateUser(username: string, password: string): Promise<any> { const user = this.users.find(u => u.username === username && u.password === password); return user ? { username: user.username } : null; } } @Injectable() class LocalStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super(); } async validate(username: string, password: string): Promise<any> { const user = await this.authService.validateUser(username, password); if (!user) { throw new UnauthorizedException(); } return user; } } @Controller('auth') class AuthController { @UseGuards(AuthGuard('local')) @Post('login') login(@Request() req) { return req.user; } } @Module({ imports: [PassportModule.register({ defaultStrategy: 'local' })], providers: [AuthService, LocalStrategy], controllers: [AuthController], }) export class AuthModule {}
Always handle errors like unauthorized access to keep your app safe.
Use HTTPS in production to protect user credentials during login.
Passport.js supports many strategies; you can add social logins easily.
Passport.js helps add login and user verification in NestJS apps.
Define strategies to control how users log in.
Protect routes using guards that check user login status.
Practice
Solution
Step 1: Understand Passport.js role
Passport.js is a library designed to handle user authentication in Node.js applications.Step 2: Connect Passport.js with NestJS
In NestJS, Passport.js is used to define login strategies and verify users securely.Final Answer:
To handle user authentication and login strategies -> Option AQuick Check:
Passport.js = Authentication [OK]
- Confusing Passport.js with database tools
- Thinking Passport.js styles UI
- Assuming Passport.js improves server speed
Solution
Step 1: Recall NestJS guard syntax
Passport strategies are applied using AuthGuard with the strategy name as a string.Step 2: Match correct syntax
The correct syntax is @UseGuards(AuthGuard('local')) to apply the local strategy guard.Final Answer:
@UseGuards(AuthGuard('local')) -> Option CQuick Check:
UseGuards with AuthGuard('strategy') [OK]
- Passing strategy class instead of string
- Omitting AuthGuard wrapper
- Using incorrect decorator syntax
async validate(username: string, password: string) {
if (username === 'user' && password === 'pass') {
return { userId: 1, username };
}
return null;
}Solution
Step 1: Analyze validate method logic
The method checks if username is 'user' and password is 'pass'. If yes, it returns a user object.Step 2: Determine output for correct credentials
For correct credentials, it returns { userId: 1, username } which is { userId: 1, username: 'user' }.Final Answer:
Returns user object { userId: 1, username: 'user' } -> Option DQuick Check:
Correct credentials return user object [OK]
- Assuming it throws error on failure
- Confusing null with undefined
- Ignoring the return statement
@UseGuards(AuthGuard(LocalStrategy))
@Get('profile')
getProfile() {
return 'User Profile';
}Solution
Step 1: Check AuthGuard parameter
AuthGuard expects a string with the strategy name, e.g., 'local', not the strategy class.Step 2: Confirm correct usage
Correct usage is @UseGuards(AuthGuard('local')), passing the strategy name as a string.Final Answer:
AuthGuard should receive strategy name as string, not class -> Option AQuick Check:
AuthGuard('strategyName') not class [OK]
- Passing strategy class instead of string
- Forgetting to import AuthGuard
- Assuming method must be async
1. Create a JWT strategy class
2. Use @UseGuards(AuthGuard('jwt')) on the route
3. Implement validate() method in strategy
4. Call AuthGuard('local') on the route
Which steps should you follow?Solution
Step 1: Understand JWT strategy usage
To protect routes with JWT, create a JWT strategy and implement validate() to verify tokens.Step 2: Apply AuthGuard with 'jwt'
Use @UseGuards(AuthGuard('jwt')) on routes to enforce JWT authentication.Step 3: Exclude local strategy for JWT protection
Using AuthGuard('local') is for login, not for protecting routes after login.Final Answer:
Steps 1, 2, and 3 only -> Option BQuick Check:
JWT strategy + AuthGuard('jwt') + validate() [OK]
- Using local strategy guard to protect routes
- Skipping validate() method in strategy
- Applying AuthGuard without strategy name
Ready to prove it?
Pass the test and this pattern moves unknown
