The local strategy helps check if a user's username and password are correct. It lets your app know who is trying to log in.
0
0
Local strategy (username/password) in NestJS
Introduction
When you want users to log in with a username and password.
When you need to protect parts of your app so only logged-in users can access them.
When you want to check user credentials before giving access.
When you want to handle login logic inside your NestJS app.
When you want to use Passport.js with NestJS for simple username/password login.
Syntax
NestJS
import { Strategy } from 'passport-local'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super(); // uses default fields: username and password } async validate(username: string, password: string): Promise<any> { const user = await this.authService.validateUser(username, password); if (!user) { throw new UnauthorizedException(); } return user; } }
The validate method checks the username and password.
Throwing UnauthorizedException stops login if credentials are wrong.
Examples
Use this if users log in with email instead of username.
NestJS
super({ usernameField: 'email' }); // This changes the field from 'username' to 'email' if your login uses email instead.
You can add a message to the exception to explain why login failed.
NestJS
async validate(username: string, password: string) { const user = await this.authService.validateUser(username, password); if (!user) { throw new UnauthorizedException('Invalid credentials'); } return user; }
Sample Program
This example shows a simple AuthService with two users. The LocalStrategy uses it to check username and password. The testLogin function simulates two login attempts: one correct and one wrong.
NestJS
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-local'; @Injectable() export class AuthService { private users = [ { id: 1, username: 'alice', password: 'wonderland' }, { id: 2, username: 'bob', password: 'builder' }, ]; async validateUser(username: string, password: string) { const user = this.users.find(u => u.username === username && u.password === password); if (user) { const { password, ...result } = user; return result; } return null; } } @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super(); } async validate(username: string, password: string) { const user = await this.authService.validateUser(username, password); if (!user) { throw new UnauthorizedException(); } return user; } } // Example usage simulation async function testLogin() { const authService = new AuthService(); const strategy = new LocalStrategy(authService); try { const user = await strategy.validate('alice', 'wonderland'); console.log('Login success:', user); } catch (e) { console.log('Login failed'); } try { const user = await strategy.validate('alice', 'wrongpass'); console.log('Login success:', user); } catch (e) { console.log('Login failed'); } } testLogin();
OutputSuccess
Important Notes
Local strategy works with Passport.js inside NestJS.
Always keep passwords safe and hashed in real apps (this example uses plain text for simplicity).
Throwing UnauthorizedException stops the login process if credentials are wrong.
Summary
Local strategy checks username and password to log users in.
Use validate method to verify credentials.
Throw an error if login fails to stop access.