Authentication with JWT in Node.js — a practical guide to JWT authentication Node.js with clear examples you can reuse in real projects.
Authentication with JWT in Node.js — 52/55 in the Node.js series. Full playlist companion: Node.js complete course on YouTube. Prefer one article? Read the complete Node.js tutorial.
Short description
JWTs are signed tokens containing user claims. The client sends `Authorization: Bearer <token>`, and middleware verifies it on protected routes.
Sign and verify JWT
const jwt = require('jsonwebtoken');
function signToken(user) {
return jwt.sign({ sub: user.id }, process.env.JWT_SECRET, { expiresIn: '1d' });
}
function auth(req, res, next) {
const header = req.headers.authorization || '';
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Unauthorized' });
}
}
app.get('/api/me', auth, (req, res) => res.json({ user: req.user }));