Node.js Authentication: JWT and Passport.js

On this page

JWT authentication is the standard for Node.js APIs. Here’s how to implement it properly with Passport.js.

Setup

Bash1 line
npm install passport passport-jwt jsonwebtoken bcryptjs

Generate Token

JavaScript9 lines
const jwt = require('jsonwebtoken');

function generateToken(user) {
  return jwt.sign(
    { id: user.id, email: user.email },
    process.env.JWT_SECRET,
    { expiresIn: '24h' }
  );
}

Passport Strategy

JavaScript10 lines
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;

passport.use(new JwtStrategy({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: process.env.JWT_SECRET
}, async (payload, done) => {
  const user = await User.findById(payload.id);
  return done(null, user || false);
}));

Protect Routes

JavaScript4 lines
app.get('/api/profile',
  passport.authenticate('jwt', { session: false }),
  (req, res) => res.json(req.user)
);

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.