With a session, the server stores the login state and gives the browser only a random ID in a cookie; with a JWT, the login state is in a signed token the client sends back, and the server checks the signature instead of looking anything up. For a typical web app with one backend, server-side sessions in an HttpOnly cookie are simpler and easier to log out; JWTs earn their complexity when several separate services must verify the same login without sharing a session store.
The question is often framed as "JWT vs cookies", but that mixes two things. A cookie is a way to carry data between browser and server. A JWT is a token format. You can put a session ID in a cookie, a JWT in a cookie, or a JWT in an Authorization: Bearer header. The real choice is where the state lives.
JWT vs session at a glance
| Server-side session | JWT | |
|---|---|---|
| What the client holds | Random ID, e.g. 32 hex characters | Signed JSON, typically a few hundred bytes |
| Where user data lives | Server (memory, Redis, database) | Inside the token |
| Per-request check | Look the ID up in the store | Verify the signature and exp |
| Log out or revoke now | Delete the server record | Not possible without extra server state |
| Readable by the client | No, the ID means nothing | Yes, the payload is only base64url-encoded |
| Works across unrelated services | Only if they share the store | Yes, anyone with the verification key |
How a session works
After the password check, the server creates a record (user ID, roles, expiry) and sends back a random identifier:
Set-Cookie: __Host-sid=5c72571ae5be21324cb9f9079dfa5b82; Path=/; Secure; HttpOnly; SameSite=Lax
The browser sends that cookie on every request, and the server looks the ID up. OWASP's Session Management Cheat Sheet requires at least 64 bits of entropy from a cryptographically secure generator; the example above is 128 bits (16 random bytes as 32 hex characters). Each attribute does a job, as documented on MDN:
HttpOnly: JavaScript can't read the cookie throughdocument.cookie, which limits the damage of an XSS bug.Secure: sent over HTTPS only.SameSite=Lax: not sent on most cross-site requests, a first defence against CSRF. MDN notes that browsers treat a cookie with noSameSiteattribute asLaxby default.- The
__Host-prefix: the browser only accepts the cookie if it hasSecure, noDomainattribute andPath=/, so a subdomain can't overwrite it. - No
ExpiresorMax-Age: MDN calls this a session cookie, deleted when the browser session ends.
Logging out means deleting the server record. OWASP stresses that this must happen on the server: clearing the cookie on the client does nothing to a copy an attacker already has.
How a JWT works
RFC 7519 defines a JWT as "a compact, URL-safe means of representing claims to be transferred between two parties." A signed JWT is three base64url parts separated by dots: header, payload, signature. Here is a real HS256 token we generated with Node.js's crypto module, 164 characters long:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMDQyIiwibmFtZSI6IkFsZXgiLCJpYXQiOjE3OTQ4MTYwMDAsImV4cCI6MTc5NDgxNjkwMH0.z3D4jLLmRVC4u8bcNIM339hZdCsFFaqR2Gu9ido2hJ8
Decode the middle part and you get the payload in plain text. No key is needed:
node -e "console.log(Buffer.from(process.argv[1].split('.')[1], 'base64url').toString())" <token>
Output:
{"sub":"1042","name":"Alex","iat":1794816000,"exp":1794816900}
Those are registered claims from RFC 7519: sub is the subject (the user), iat is when it was issued, and exp is the time "on or after which the JWT MUST NOT be accepted". Both times are NumericDate values, seconds since 1970-01-01 UTC; here they are 2026-11-16 08:00 and 08:15 UTC, a 15-minute token. The signature proves nobody changed the payload. It does not hide it, so never put anything secret in a signed JWT.
The server verifies the signature with its key and checks exp, with no database lookup. That is the whole appeal: any service holding the verification key (for RS256 or ES256, just a public key) can trust the token on its own.
The logout problem with JWTs
A validly signed JWT stays valid until exp. If a user clicks "log out", changes their password, or is banned by an admin, a copy of their token still works. The usual fixes:
- Short access tokens plus a refresh token. Access tokens live for minutes, such as the 15-minute token above. A longer-lived refresh token, stored server-side and revocable, gets new ones. Revoking the refresh token ends the session within one access-token lifetime.
- A denylist. Store the
jti(unique token ID, also from RFC 7519) of revoked tokens and check it on every request.
Both put server-side state back. That is the honest trade-off: a JWT system that supports instant logout is a session system with extra steps.
Where to store a JWT in the browser
OWASP's Session Management Cheat Sheet says not to store authentication tokens, session IDs or JWTs in localStorage or sessionStorage, because any script on the page can read them, so a single XSS bug exposes every token. Its recommendation is an HttpOnly; Secure; SameSite=Strict cookie or a backend-for-frontend, where the browser only holds a session cookie and a server-side component holds the tokens. Once a JWT sits in a cookie, the browser sends it automatically, and you need the same CSRF protection as for a session cookie.
Size matters too. MDN notes a typical limit of about 4 KB per cookie. A JWT carrying roles, permissions and profile data grows quickly, and it is sent on every request.
JWT mistakes that break security
RFC 8725, the JWT Best Current Practices, lists the classic failures:
- Trusting
algfrom the token. Some libraries accepted"alg": "none"and "validated" tokens without checking any signature. Libraries must let you fix the allowed algorithms; pass that list explicitly when you verify. - Weak HMAC keys. RFC 8725 says human-memorizable passwords must not be used directly as an HS256 key, because a captured token can be brute-forced offline. Use at least 32 random bytes.
- Skipping
aud. If one issuer serves several applications, tokens must carry an audience, and each application must reject tokens not meant for it.
Which should you use?
- Server-rendered site or single-page app with its own backend: sessions in an
__Host-,HttpOnly,Securecookie. Instant logout, nothing readable on the client, a small cookie. - Several services or a third-party API trusting one login server: short-lived JWT access tokens, usually issued through OAuth 2.0 or OpenID Connect, with revocable refresh tokens. See API key vs OAuth for how those flows fit together.
- Mobile apps calling an API: either works; bearer tokens are common because there is no cookie jar to rely on. Keep them in the platform's secure storage.
If you pick JWTs only because "sessions don't scale", measure first. A session lookup is one key read from Redis or an indexed table, and a store shared by all servers removes the "sticky session" problem.
Frequently asked questions
- Can I store a JWT in a cookie?
- Yes, and for browser apps it is usually the safer place. A JWT in an HttpOnly, Secure cookie can't be read by JavaScript, so an XSS bug can't copy it out. You then need the same CSRF protections as with a session cookie, such as SameSite and anti-CSRF tokens. JWT and cookie are not opposites: one is a token format, the other is a transport.
- Is a JWT encrypted?
- Usually not. A normal JWT is signed, not encrypted: the header and payload are base64url-encoded JSON that anyone holding the token can decode. The signature only proves the content wasn't changed. Don't put secrets or personal data in the payload unless you use an encrypted JWT (JWE).
- How do I log a user out when using JWTs?
- Deleting the token on the client is not enough if it was copied, because the server accepts any validly signed token until its exp time. Keep access tokens short-lived (minutes), and either keep a server-side denylist of revoked token IDs (the jti claim) or rely on revoking the longer-lived refresh token. Both bring back the server-side lookup that JWTs were meant to avoid.
- Are sessions harder to scale than JWTs?
- Less than often claimed. Sessions need a store every server can reach, such as Redis or the database, and one fast key lookup per request. Most applications already query a database on every request, so the extra lookup rarely matters. JWTs help most when separate services that don't share a store need to trust the same login.