How to Use Passport JWT Strategy in Express for Authentication
To use
passport-jwt strategy in Express, install passport and passport-jwt, then configure Passport with a JWT strategy that extracts the token from requests and verifies it. Use passport.authenticate('jwt') middleware to protect routes by validating the JWT sent by clients.Syntax
The main parts of using Passport JWT strategy are:
- Importing modules:
passportandpassport-jwt. - Setting options: Define how to extract the JWT from requests and the secret key to verify it.
- Creating the strategy: Use
JwtStrategywith a verify callback to check the token payload. - Initializing Passport: Use
passport.initialize()middleware in Express. - Protecting routes: Use
passport.authenticate('jwt', { session: false })as middleware.
javascript
import express from 'express'; import passport from 'passport'; import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'; const app = express(); const opts = { jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'your_jwt_secret', }; passport.use(new JwtStrategy(opts, (jwt_payload, done) => { // Find user by id in jwt_payload // Call done(null, user) if found, else done(null, false) })); app.use(passport.initialize()); app.get('/protected', passport.authenticate('jwt', { session: false }), (req, res) => { res.json({ message: 'You accessed a protected route!' }); });
Example
This example shows a simple Express server using Passport JWT strategy to protect a route. It verifies a JWT sent in the Authorization header and returns user info if valid.
javascript
import express from 'express'; import passport from 'passport'; import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'; const app = express(); const PORT = 3000; const users = [{ id: 1, username: 'alice' }]; const opts = { jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'secret123', }; passport.use(new JwtStrategy(opts, (jwt_payload, done) => { const user = users.find(u => u.id === jwt_payload.id); if (user) { return done(null, user); } else { return done(null, false); } })); app.use(passport.initialize()); app.get('/protected', passport.authenticate('jwt', { session: false }), (req, res) => { res.json({ message: 'Hello ' + req.user.username + ', you accessed a protected route!' }); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when using Passport JWT strategy include:
- Not calling
passport.initialize()middleware before protected routes. - Using the wrong method to extract the JWT (e.g., not using
ExtractJwt.fromAuthHeaderAsBearerToken()when token is in Authorization header). - Forgetting to set
{ session: false }inpassport.authenticateto disable sessions. - Not handling the
donecallback properly in the verify function, causing authentication to fail silently.
Example of a wrong and right usage:
javascript
// Wrong: Missing passport.initialize() app.get('/protected', passport.authenticate('jwt'), (req, res) => { res.send('Protected'); }); // Right: Include passport.initialize() and disable sessions app.use(passport.initialize()); app.get('/protected', passport.authenticate('jwt', { session: false }), (req, res) => { res.send('Protected'); });
Quick Reference
Tips for using Passport JWT strategy in Express:
- Always extract JWT from the Authorization header as a Bearer token.
- Keep your JWT secret safe and do not hardcode it in production.
- Use
passport.initialize()before any route that uses Passport. - Set
{ session: false }inpassport.authenticateto avoid session support. - Verify the JWT payload carefully and handle user lookup securely.
Key Takeaways
Install and configure passport and passport-jwt to use JWT authentication in Express.
Use ExtractJwt.fromAuthHeaderAsBearerToken() to get the token from request headers.
Always call passport.initialize() middleware before protected routes.
Use passport.authenticate('jwt', { session: false }) to protect routes without sessions.
Handle the verify callback properly to find and validate the user from the JWT payload.