Implementation·7 min read·Updated October 21, 2026

Using JWT Secrets with Express: Authentication Middleware and Best Practices

Express.js remains one of the world's most popular Node.js frameworks. Here is a production-grade, hardened authentication middleware implementation using `jsonwebtoken` with explicit algorithm whitelisting and structured error responses.

Production Express Auth Middleware

This middleware extracts the token from the `Authorization: Bearer <token>` header, verifies the signature against `process.env.JWT_SECRET`, checks token expiration, and attaches the decoded user payload to `req.user`.
javascriptHardened Express.js JWT verification middleware
const jwt = require('jsonwebtoken');

function requireAuth(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing or malformed Authorization header' });
  }

  const token = authHeader.split(' ')[1];

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET, {
      algorithms: ['HS256'],
    });
    req.user = decoded;
    next();
  } catch (err) {
    if (err.name === 'TokenExpiredError') {
      return res.status(401).json({ error: 'Token has expired', code: 'TOKEN_EXPIRED' });
    }
    return res.status(401).json({ error: 'Invalid authentication token' });
  }
}
Generate in Browser

Need a cryptographically secure JWT secret right now?

Generate 128 to 512-bit keys in Hex or Base64 using Web Crypto with zero server transmission.

Launch Generator

Frequently Asked Questions

Can I store the JWT in an HttpOnly cookie instead of Bearer header?

Yes, HttpOnly SameSite=Strict cookies protect tokens from cross-site scripting (XSS) attacks in single-page applications.

Using JWT Secrets with Express – Middleware & Security Guide | JWT Secret Key Generator | JWT Secret Key Generator