How to implement authentication middleware in Express

· Category: Node.js

Short answer

Create a middleware function that checks for a valid token or session, attaches user data to the request, and calls next() or returns a 401 response.

Steps

  1. Extract the token from headers: const token = req.headers.authorization?.split(' ')[1];.
  2. Verify the token using jsonwebtoken.verify(token, secret).
  3. If valid, attach user info: req.user = decoded; and call next().
  4. If invalid or missing, return res.status(401).json({ message: 'Unauthorized' });.
  5. Apply the middleware to protected routes: app.get('/profile', authMiddleware, handler);.

Tips

  • Store JWT secrets in environment variables, never hardcode them.
  • Consider using refresh tokens for long-lived sessions and access tokens with short expiry.

Common issues

  • Tokens sent without the Bearer prefix require different parsing logic.
  • Clock skew between servers can cause valid tokens to fail verification if expiry margins are too tight.