JWT, cookies, CORS and security headers
Tokens and the browser's rules: what is inside a JWT, where to store tokens, what CORS really controls and the headers worth sending.
On the roadmap:Intermediate · step 7: Secure by design
Lesson 4 of 5 · 13 min read · quiz · exercise
Cookies and sessions, quickly
A session keeps a user logged in. The usual approach: after login the server creates a random session id, stores session data server-side, and sends the id in a cookie. (Passwords and sessions are detailed in their own lesson.) Good cookie flags:
| Flag | Effect |
|---|---|
HttpOnly | JavaScript cannot read it, limiting theft through XSS |
Secure | Sent only over HTTPS |
SameSite=Lax/Strict | Limits cross-site sending, reducing CSRF |
Path, Domain | Limit where it is sent |
Max-Age / Expires | Lifetime; keep session cookies short-lived with renewal |
JSON Web Tokens (JWT)
A JWT is a compact, signed token with three dot-separated, base64url parts: header (algorithm), payload (claims) and signature.
Figure SDA-NSD-04-1 · Anatomy and checking of a JWT · © forcsguy.com
Why use them: the API can verify a token without a database lookup, which suits services and mobile apps. The cost: a stateless token is hard to revoke before it expires.
Good practice
- Keep access tokens short-lived (minutes) and use refresh tokens (stored carefully, rotated, revocable) to get new ones.
- Always verify signature,
exp,iss(issuer) andaud(audience); pin the algorithm. - A JWT is signed, not encrypted: do not put sensitive data in it (use JWE if you must encrypt).
- Where to store in a browser: HttpOnly cookies resist XSS theft but need CSRF protection;
localStorageis readable by any script, so an XSS leaks the token. There is no perfect answer: choose with your threat model, and prevent XSS first. - For simple server-rendered apps, server-side sessions are often simpler and easier to revoke than JWTs. (Federated login with OAuth and OpenID Connect is in the SSO lesson.)
Same-origin policy and CORS
Browsers enforce the same-origin policy: a page from one origin (scheme, host and port) cannot read responses from another origin. CORS (cross-origin resource sharing) is how a server opts in to being read by specific other origins.
Figure SDA-NSD-04-2 · A cross-origin request with a preflight · © forcsguy.com
Key points:
- CORS protects users' browsers, not your server. It does not stop
curl, scripts or other servers from calling your API; you still need authentication and authorisation. - A simple request (GET or simple POST with plain headers) is sent directly; the browser only decides whether the page may read the response. Other requests get a preflight.
- Configure exact origins, not
*, when credentials are involved.Access-Control-Allow-Credentials: truecannot be combined with*. Never blindly echo theOriginheader. - Limit allowed methods and headers; cache preflights with
Access-Control-Max-Age.
Security headers worth sending
| Header | Purpose |
|---|---|
Strict-Transport-Security | Tell browsers to use HTTPS only for your domain |
Content-Security-Policy | Restrict script, style, frame and connection sources; mitigates XSS and clickjacking |
X-Content-Type-Options: nosniff | Stop browsers guessing content types |
Referrer-Policy | Limit referrer information sent to others |
Permissions-Policy | Turn off powerful browser features you do not use |
Cross-Origin-Opener-Policy / Cross-Origin-Resource-Policy | Isolate your pages from other origins |
Caching headers and compression
Cache-Controlcontrols caching:public, max-age=31536000, immutablefor fingerprinted static files;no-storefor sensitive responses;privatefor per-user responses that shared caches must not store.ETag/Last-Modifiedallow cheap revalidation (a 304 response with no body).- Compression (gzip, Brotli) shrinks text responses a lot. One caution: compressing responses that mix secrets with attacker-controlled text over TLS can enable attacks such as BREACH, so avoid reflecting secrets and use per-request tokens.
- Do not cache authenticated pages in shared caches by accident; set
Varycorrectly.
Checklist
Cookies: HttpOnly, Secure, SameSite. Tokens: short-lived, verified fully, no secrets inside. CORS: exact origins, minimal methods. Headers: HSTS, CSP, nosniff, frame protection. Caching: private or no-store for user data.
Real-world reading
Related reading
- MDN: Cross-Origin Resource Sharing (CORS)MDN contributors · MozillaDocumentation
- Introduction to JSON Web TokensAuth0 · jwt.ioDocumentation
- RFC 6749: The OAuth 2.0 Authorization FrameworkIETFDocumentation
- MDN: HTTP cachingMDN contributors · MozillaDocumentation
Show 6 moreShow fewer
- HTTP/3: the past, the present, and the futureCloudflareBlogs
- System Design 101ByteByteGo · ByteByteGoHqGitHub
- High Performance Browser NetworkingIlya Grigorik · O'ReillyBooks
- RFC 9114: HTTP/3IETFDocumentation
- Distributed SecurityMicrosoft engineers · MicrosoftCase Studies
- TripAdvisor Architecture - 40M Visitors, 200M Dynamic Page Views, 30TB Data - High Scalability -High Scalability engineers · High ScalabilityCase Studies
Check your understanding
Question 1 of 3
0 correct so far
What does the signature on a JWT guarantee?
Go deeper
- JSON Web Token introduction by jwt.io: structure and use
- MDN: Cross-Origin Resource Sharing by MDN Web Docs: the definitive explanation
Topics covered in this lesson
Practise it: Stateless tokens scale out
Everything below is already set up for this lesson: change the design, run the traffic, and see whether you meet the goal.
- 1The task
- 2Build and test
Sessions kept in server memory pin each user to one machine. Signed tokens let any server answer, so capacity is just a count of servers.
Goal: Under 1% errors at 1,600 requests per second, within $650 a month.
Any server can verify a signed token, so you can add servers freely.
Try it yourself
A single-page app on app.example.com calls an API on api.example.com. Choose how to authenticate and how to configure CORS, and name three pitfalls to avoid.
Click what a strong design here would need:
More in Building blocks
© 2026 forcsguy.com. Original lesson text and diagrams. Books and sites linked above belong to their authors.