How to Implement Authentication in Express: Simple Guide
To implement authentication in
Express, use middleware like Passport.js which handles login strategies and session management. Set up express-session for session handling, configure Passport with a strategy like LocalStrategy, and create routes to handle login and logout.Syntax
Authentication in Express typically involves these parts:
express-session: Middleware to manage user sessions.passport.initialize()andpassport.session(): Middleware to initialize Passport and manage persistent login sessions.passport.use(): To define the authentication strategy (e.g., local username/password).- Routes to handle login, logout, and protected content.
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(session({ secret: 'secretKey', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); passport.use(new LocalStrategy( function(username, password, done) { // Verify username and password here } )); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { // Find user by id here }); app.post('/login', passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/login' }));
Example
This example shows a simple Express app with local authentication using Passport.js. It includes user login, session handling, and a protected 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 })); // Simple user store const users = [{ id: 1, username: 'user', password: 'pass' }]; app.use(session({ secret: 'secretKey', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); 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 || false); }); function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) return next(); 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.post('/login', passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/login' })); app.get('/dashboard', ensureAuthenticated, (req, res) => { res.send(`Hello, ${req.user.username}. Welcome to your dashboard.`); }); app.get('/logout', (req, res, next) => { req.logout(function(err) { if (err) { return next(err); } res.redirect('/login'); }); }); app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
Server running on http://localhost:3000
When visiting /login, a login form appears.
After successful login with username 'user' and password 'pass', user is redirected to /dashboard showing a welcome message.
Accessing /dashboard without login redirects to /login.
Common Pitfalls
- Not using
express-sessionor misconfiguring it causes sessions not to persist. - Forgetting to call
passport.initialize()andpassport.session()middleware in the correct order. - Not implementing
serializeUseranddeserializeUserproperly, which breaks session handling. - Storing passwords in plain text instead of hashing them (use bcrypt or similar in real apps).
- Not protecting routes with authentication checks, allowing unauthorized access.
javascript
/* Wrong: Missing session middleware */ app.use(passport.initialize()); app.use(passport.session()); /* Right: Include session middleware before passport.session() */ app.use(session({ secret: 'secretKey', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session());
Quick Reference
- Use
express-sessionto enable sessions. - Initialize Passport with
passport.initialize()andpassport.session(). - Define a strategy like
LocalStrategyfor username/password. - Implement
serializeUseranddeserializeUserto manage user data in sessions. - Protect routes by checking
req.isAuthenticated().
Key Takeaways
Use express-session and Passport.js middleware to manage authentication in Express.
Always implement serializeUser and deserializeUser for session support.
Protect routes by checking if the user is authenticated with req.isAuthenticated().
Never store passwords in plain text; use hashing in real applications.
Initialize session middleware before passport.session() to avoid errors.