Token verification
When a request comes in with a JWT, the server checks that it was signed with your secret and hasn't expired. If it's valid, you can trust the user info inside it.
import jwt from "jsonwebtoken"
function verifyToken(token) {
try {
return jwt.verify(token, process.env.JWT_SECRET)
// { id: 1, iat: ..., exp: ... }
} catch {
return null // invalid or expired
}
}
// Client sends it in the Authorization header
// Authorization: Bearer eyJhbGciOi...
const token = req.headers.authorization?.split(" ")[1]