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
- Extract the token from headers:
const token = req.headers.authorization?.split(' ')[1];. - Verify the token using
jsonwebtoken.verify(token, secret). - If valid, attach user info:
req.user = decoded;and callnext(). - If invalid or missing, return
res.status(401).json({ message: 'Unauthorized' });. - 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
Bearerprefix require different parsing logic. - Clock skew between servers can cause valid tokens to fail verification if expiry margins are too tight.