Launch offer
Business website $150 USD Custom plugin $200 USD Ready in 5 days
Get a quote
Node.js

Authentication with JWT in Node.js

Implement stateless auth by signing and verifying JSON Web Tokens in Express APIs.

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 }));

Leave a reply

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