Authentication & JWT
Authentication verifies who a user is. A common stateless approach in APIs is JSON Web Tokens (JWT) — signed tokens that encode user information and can be verified without a database lookup.
After login, the server issues a JWT; the client sends it back on future requests (usually in an Authorization header) to prove identity.
Issuing a token
Use a library like `jsonwebtoken` to sign a payload (like a user ID) with a secret key, producing a token string.
Verifying a token
Middleware can verify the token on protected routes, rejecting requests with missing or invalid tokens.
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 1 }, 'secretKey', { expiresIn: '1h' });
console.log(token);eyJhbGciOiJIUzI1NiIs...sign() creates a token containing the payload, expiring after 1 hour.
function auth(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
try {
req.user = jwt.verify(token, 'secretKey');
next();
} catch {
res.status(401).json({ error: 'Unauthorized' });
}
}401 if token invalid, otherwise proceedsMiddleware verifies the token and attaches decoded data to req.user.
Key points
- JWTs are signed tokens proving a user's identity.
- jwt.sign() creates a token; jwt.verify() checks it.
- Tokens are usually sent in the Authorization header.
- JWT-based auth is stateless — no server-side session storage needed.
