How to Use Passport Local Strategy in Express for Authentication
To use
passport-local strategy in Express, first install passport and passport-local, then configure Passport with a local strategy that verifies user credentials. Use passport.authenticate('local') middleware in your login route to handle authentication.Syntax
The passport-local strategy requires you to create a new instance of LocalStrategy where you define how to verify a username and password. Then, you use passport.use() to add this strategy to Passport. Finally, apply passport.authenticate('local') as middleware in your Express route to authenticate users.
LocalStrategy: Constructor to define verification logic.passport.use(): Registers the strategy.passport.authenticate('local'): Middleware to trigger authentication.
javascript
import passport from 'passport'; import { Strategy as LocalStrategy } from 'passport-local'; passport.use(new LocalStrategy( function(username, password, done) { // Verify username and password here // Call done(null, user) if success // Call done(null, false) if failure } )); app.post('/login', passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/login', failureFlash: true }));
Example
This example shows a simple Express app using Passport local strategy to authenticate a user with a hardcoded username and password. It demonstrates setting up Passport, session handling, and protecting a route.
javascript
import express from 'express'; import session from 'express-session'; import passport from 'passport'; import { Strategy as LocalStrategy } from 'passport-local'; const app = express(); app.use(express.urlencoded({ extended: false })); app.use(session({ secret: 'secret', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); // User data for demo const users = [{ id: 1, username: 'user', password: 'pass' }]; passport.use(new LocalStrategy((username, password, done) => { const user = users.find(u => u.username === username); if (!user) return done(null, false, { message: 'Incorrect username.' }); if (user.password !== password) return done(null, false, { message: 'Incorrect password.' }); return done(null, user); })); passport.serializeUser((user, done) => done(null, user.id)); passport.deserializeUser((id, done) => { const user = users.find(u => u.id === id); done(null, user); }); app.post('/login', passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/login' })); app.get('/dashboard', (req, res) => { if (req.isAuthenticated()) { res.send('Welcome to your dashboard, ' + req.user.username); } else { res.redirect('/login'); } }); app.get('/login', (req, res) => { res.send('<form method="post" action="/login">\n' + '<input name="username" placeholder="Username"/>\n' + '<input name="password" type="password" placeholder="Password"/>\n' + '<button type="submit">Login</button>\n' + '</form>'); }); app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
Server running on http://localhost:3000
When visiting /login, a form appears. Submitting username 'user' and password 'pass' redirects to /dashboard showing "Welcome to your dashboard, user". Wrong credentials redirect back to /login.
Common Pitfalls
- Not calling
passport.initialize()andpassport.session()middleware in Express. - Forgetting to serialize and deserialize user for session support.
- Not parsing form data with
express.urlencoded()before authentication. - Using incorrect field names; by default,
LocalStrategyexpectsusernameandpasswordfields. - Not handling asynchronous user verification properly.
javascript
/* Wrong: Missing express.urlencoded middleware */ app.post('/login', passport.authenticate('local')); /* Right: Include body parser before authentication */ app.use(express.urlencoded({ extended: false })); app.post('/login', passport.authenticate('local'));
Quick Reference
- Install packages:
npm install passport passport-local express-session - Setup Passport: Use
passport.use(new LocalStrategy(...)) - Middleware order:
express.urlencoded(),express-session,passport.initialize(),passport.session() - Routes: Use
passport.authenticate('local')in login POST route - Session: Implement
serializeUseranddeserializeUser
Key Takeaways
Always configure Passport with a LocalStrategy that verifies username and password.
Use express.urlencoded middleware before Passport to parse form data.
Call passport.initialize() and passport.session() middleware in correct order.
Implement serializeUser and deserializeUser for session management.
Use passport.authenticate('local') middleware in your login route.