How to Use JWT in Express for Authentication
To use
jwt in Express, install the jsonwebtoken package, then generate tokens with jwt.sign() and verify them with jwt.verify(). Use middleware to protect routes by checking the token sent in request headers.Syntax
Here is the basic syntax to generate and verify JWT tokens in Express using the jsonwebtoken package:
jwt.sign(payload, secret, options): Creates a token with user data and a secret key.jwt.verify(token, secret): Checks if the token is valid using the secret key.- Use middleware to extract the token from request headers and verify it before allowing access.
javascript
const jwt = require('jsonwebtoken'); // Generate a token const token = jwt.sign({ userId: 123 }, 'your-secret-key', { expiresIn: '1h' }); // Verify a token jwt.verify(token, 'your-secret-key', (err, decoded) => { if (err) { // Token invalid or expired } else { // Token valid, decoded contains the payload } });
Example
This example shows a simple Express app that creates a JWT on login and protects a route using middleware that verifies the token.
javascript
import express from 'express'; import jwt from 'jsonwebtoken'; const app = express(); app.use(express.json()); const SECRET_KEY = 'your-secret-key'; // Login route to generate token app.post('/login', (req, res) => { const { username } = req.body; if (!username) { return res.status(400).json({ message: 'Username required' }); } // Create token with username payload const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '1h' }); res.json({ token }); }); // Middleware to verify token function authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) return res.status(401).json({ message: 'Token missing' }); jwt.verify(token, SECRET_KEY, (err, user) => { if (err) return res.status(403).json({ message: 'Token invalid' }); req.user = user; next(); }); } // Protected route app.get('/protected', authenticateToken, (req, res) => { res.json({ message: `Hello, ${req.user.username}! This is protected.` }); }); app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
POST /login with {"username":"alice"} returns {"token":"<jwt_token>"}
GET /protected with header Authorization: Bearer <jwt_token> returns {"message":"Hello, alice! This is protected."}
Common Pitfalls
- Forgetting to keep the secret key safe and consistent causes token verification to fail.
- Not sending the token in the
Authorizationheader or sending it incorrectly (missing 'Bearer' prefix). - Not handling token expiration properly leads to unauthorized errors.
- Using synchronous
jwt.verifywithout error handling can crash the app.
none
/* Wrong: Missing 'Bearer' prefix in header */ // Client sends: Authorization: <token> /* Right: Include 'Bearer' prefix */ // Client sends: Authorization: Bearer <token>
Quick Reference
Remember these key points when using JWT in Express:
- Use
jsonwebtokenpackage for token creation and verification. - Keep your secret key private and secure.
- Send tokens in the
Authorizationheader asBearer <token>. - Protect routes with middleware that verifies tokens.
- Handle token expiration to prompt re-login.
Key Takeaways
Use the jsonwebtoken package to create and verify JWTs in Express.
Protect routes by verifying tokens in middleware before allowing access.
Send JWTs in the Authorization header with the Bearer scheme.
Keep your secret key secure and consistent across your app.
Handle token expiration to maintain secure sessions.