JSON Web Tokens (JWTs) are the most common way to implement stateless authentication in Express REST APIs. This lesson builds a complete login and protected-route flow using the jsonwebtoken package.
How JWT Authentication Works
A JWT is a compact, signed string encoding a payload (like a user ID) and an expiration time. The server signs it with a secret key at login time and hands it to the client; the client sends it back, usually in an Authorization: Bearer <token> header, on every subsequent request.
Because the signature can be verified without any database lookup, the server doesn't need to store session state, any server instance holding the same secret can verify any valid token.
Short-lived access tokens (minutes to an hour) limit exposure if leaked, but require a way to renew them without forcing the user to log in again. A common pattern issues a longer-lived, more carefully guarded refresh token (often in an httpOnly cookie) that can be exchanged for a new access token.
Storing JWTs in localStorage for browser apps, exposing them to XSS attacks, prefer httpOnly cookies when possible.
Using a long-lived access token with no refresh flow, forcing an awkward tradeoff between security and user experience.
Hardcoding the JWT secret in source code instead of an environment variable.
Not handling jwt.verify() throwing on expired tokens, crashing the request instead of returning a clean 401.
Key Takeaways
JWTs let servers verify identity without a database lookup or server-side session storage.
The Authorization: Bearer <token> header is the standard way to send a JWT on each request.
Short-lived access tokens paired with a refresh token balance security and user experience.
Always keep JWT secrets in environment variables, never in source code.
Pro Tip
Set access token expiry short (15 minutes to 1 hour) and rely on a refresh token flow for longer sessions, this limits the damage window if an access token is ever intercepted.
You now know how to implement JWT authentication. Next, compare it with the traditional Session Authentication approach.