How to Verify JWT Token in Express: Simple Guide
To verify a
JWT token in Express, use the jsonwebtoken package's verify() method inside middleware. This method checks the token's signature and expiration, allowing you to protect routes by validating the token before proceeding.Syntax
The jsonwebtoken package provides the verify(token, secretOrPublicKey, [options], callback) method to check a JWT token's validity.
token: The JWT string to verify.secretOrPublicKey: The secret key or public key used to sign the token.options: Optional settings like algorithms or expiration checks.callback: Function called with error or decoded token payload.
javascript
jwt.verify(token, secretOrPublicKey, options, (err, decoded) => {
if (err) {
// token invalid or expired
} else {
// token valid, decoded contains payload
}
});Example
This example shows how to create Express middleware to verify a JWT token sent in the Authorization header as a Bearer token. If valid, it allows access; if not, it sends a 401 error.
javascript
import express from 'express'; import jwt from 'jsonwebtoken'; const app = express(); const SECRET_KEY = 'your-secret-key'; // Middleware to verify JWT token function verifyToken(req, res, next) { const authHeader = req.headers['authorization']; if (!authHeader) return res.status(401).json({ message: 'No token provided' }); const token = authHeader.split(' ')[1]; // Bearer token if (!token) return res.status(401).json({ message: 'Malformed token' }); jwt.verify(token, SECRET_KEY, (err, decoded) => { if (err) return res.status(401).json({ message: 'Invalid or expired token' }); req.user = decoded; // Save decoded payload for next handlers next(); }); } // Protected route example app.get('/protected', verifyToken, (req, res) => { res.json({ message: 'Access granted', user: req.user }); }); // Start server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
// When accessing /protected with valid token:
// { "message": "Access granted", "user": { ...decoded payload... } }
// With no or invalid token:
// { "message": "No token provided" } or { "message": "Invalid or expired token" }
Common Pitfalls
- Not sending the token in the
Authorizationheader or using wrong format (should beBearer <token>). - Using the wrong secret key or public key to verify the token.
- Not handling token expiration errors properly.
- Forgetting to call
next()in middleware after successful verification.
javascript
/* Wrong: Not splitting Bearer token */ const token = req.headers['authorization']; // token includes 'Bearer ' /* Right: Extract token properly */ const token = req.headers['authorization']?.split(' ')[1];
Quick Reference
Remember these key points when verifying JWT tokens in Express:
- Use
jsonwebtoken.verify()with your secret key. - Extract token from
Authorizationheader asBearer <token>. - Handle errors like invalid or expired tokens gracefully.
- Attach decoded payload to
reqfor use in later middleware or routes.
Key Takeaways
Use jsonwebtoken's verify() method inside Express middleware to check JWT tokens.
Always extract the token from the Authorization header as a Bearer token.
Handle errors like missing, invalid, or expired tokens by sending 401 responses.
Attach the decoded token payload to the request object for downstream use.
Call next() after successful verification to continue request handling.