6 min read
ā¢Question 7 of 28mediumWhat is JWT and how does it work?
Understanding JSON Web Tokens.
What You'll Learn
- JWT structure
- How JWT works
- Implementation example
JWT Structure
A JWT has three parts separated by dots:
code.jsJavaScript
header.payload.signature
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjF9.signature1. Header
data.jsonJSON
{ "alg": "HS256", "typ": "JWT" }2. Payload
data.jsonJSON
{ "userId": 1, "email": "john@example.com", "exp": 1234567890 }3. Signature
HMACSHA256(base64(header) + "." + base64(payload), secret)
Implementation
code.jsJavaScript
const jwt = require('jsonwebtoken');
// Create token
const token = jwt.sign(
{ userId: user.id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '24h' }
);
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// { userId: 1, email: 'john@example.com', iat: ..., exp: ... }
// Middleware
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}