SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • OSI Model
  • IP Address
  • TCP vs UDP
  • HTTP / HTTPS
  • DNS
  • Proxy vs Reverse Proxy
  • Checksums
  • HTTP/1.1 vs HTTP/2 vs HTTP/3
  • Cookies and CORS
  • Subnets, CIDR and NAT
  • Firewalls and VPN
  • Ports and Sockets
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Networking

Cookies and CORS

How browsers remember you, and the rules that decide which websites may call which servers.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Cookies are small pieces of data that a website asks your browser to keep and send back on later requests. CORS (Cross-Origin Resource Sharing) is the set of rules that decides when a web page from one site may read answers from a server on a different site.

  • HTTP forgets you after every request. A cookie is how the server recognises you again (a session, a cart, a preference).
  • Browsers have a safety rule, the same-origin policy: JavaScript on one site may not read data from another site by default.
  • CORS is how a server says "this other site is allowed to read my answers", using special response headers.
  • CORS is enforced by the browser. It protects the person using the browser. It is not a way to lock a server against other programs.

02Concept: What is it?

Cookies: a name tag for a forgetful server

HTTP is stateless: each request stands alone. After you log in, the server needs a way to know the next request is still you. It sends a Set-Cookie header. Your browser stores the cookie and adds a Cookie header to every later request to that site.

One login, then a normal request
HTTP/1.1 200 OK
Set-Cookie: sid=a1b2c3; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=3600

GET /orders HTTP/1.1
Host: shop.example.com
Cookie: sid=a1b2c3
How a cookie travels
🌐Browserstores the cookie
→↓login
πŸ–₯️Servercreates a session
←Set-Cookie
πŸͺCookiesid=a1b2c3
The server hands out the cookie once. The browser then sends it back on its own, every time.

Same-origin policy and CORS

An origin is the trio scheme + host + port. https://app.example.com and https://api.example.com are different origins (the host differs). So are http:// and https://, and so are two different ports.

Without a safety rule, any web page you open could call your bank's website using your logged-in cookies and read your balance. So browsers only let JavaScript read responses from the same origin. When a legitimate site needs to share, the server adds CORS headers that say who may read.

A cross-origin call
πŸ“„Pageapp.example.com
→↓fetch()
πŸ–₯️APIapi.example.com
←Access-Control-Allow-Origin
πŸ›‘οΈBrowser checkallowed? show it
The browser checks the response headers. If the server did not allow this page, JavaScript is not allowed to see the answer.
🧠CORS protects the reader, not the server
A blocked CORS request often still reaches the server and runs. The browser only refuses to show the answer to JavaScript. Tools like curl ignore CORS completely. Never use CORS as your login or security check.

03Real-Life Example

🍡The Hotel Key Card and the Front Desk
You check in to a hotel and get a key card. Later, you do not show your passport again. You tap the card, and the door recognises you. That card is the cookie. Now imagine a stranger from another hotel phones the front desk and says, "Please read me the guest list." The desk checks a short list of approved callers. If the stranger is not on it, the desk refuses to share. That list is CORS.
Hotel
Web
Key card given at check-in
Set-Cookie after login
Tapping the card at each door
The browser sends Cookie on every request
Card only works in this hotel
Cookie is tied to a domain (and path)
Card that expires at check-out
Max-Age or Expires on the cookie
Staff-only card that guests cannot copy
HttpOnly: JavaScript cannot read it
List of approved callers at the front desk
Access-Control-Allow-Origin
Asking the desk first: are you allowed to ask?
The preflight (OPTIONS) request
Preflight: ask first, then act
πŸ™‹Browserabout to send a JSON POST
→↓OPTIONS: may I?
πŸ–₯️ServerAllow-Methods: POST
←yes
πŸ“¨Real requestnow sent

04Why Do We Need It?

πŸ”‘Remember the user
Cookies are the simplest way to keep a login or a shopping cart between requests.
🧱Stop snooping pages
The same-origin policy stops a random page from reading your email or bank data through your own browser.
🀝Share on purpose
Real apps have a web page on one domain and an API on another. CORS is the controlled way to allow that.
πŸ›‘οΈSafer defaults
HttpOnly, Secure and SameSite on cookies cut off whole families of attacks.
πŸŽ›οΈFine control
A server can allow one origin, certain methods and certain headers, and say whether cookies may be included.
🧭Clear rules
Because the rules are standard, every browser behaves the same way.
Cookies let a forgetful server remember you. CORS lets a server decide which other websites may read its answers.

05Where Do We Use It?

πŸ”Login sessions
A session id in a cookie is the classic way to stay logged in.
πŸ›’Shopping carts
A cart id or a saved preference travels in a cookie.
🧩Single page apps
A React or Vue app at app.example.com calls api.example.com. That needs CORS.
🧰Public APIs
A public API often sends Allow-Origin for browser use. Server-to-server calls do not need it.
πŸ–ΌοΈFonts and CDNs
Fonts and some scripts loaded from a CDN need CORS headers in certain cases.
πŸ“ŠAnalytics and ads
Third-party cookies are used to recognise the same visitor on many sites. Browsers are limiting them.

06Types / Parts / How It Works

Cookie attributes you should know

AttributeWhat it doesWhy it matters
SecureSend the cookie only over HTTPSStops it from leaking on plain HTTP
HttpOnlyJavaScript cannot read itLimits damage if a script is injected (XSS)
SameSite=StrictSent only when the request comes from the same siteStrongest defence against CSRF, but a link from another site arrives logged out
SameSite=LaxAlso sent on normal top-level link clicks (GET), but not on cross-site POSTs or background requestsA good default for login cookies
SameSite=NoneSent on cross-site requests (needs Secure)Needed for embedded widgets and some cross-site APIs
Domain / PathWhich hosts and paths receive the cookieKeep the scope as narrow as possible
Max-Age / ExpiresHow long it lives. Without them it is a session cookie, which goes away when the browser closesPersistent cookies stay for days or months

Simple requests and preflighted requests

Does the browser ask first?
Simple: no preflight
πŸ“₯GET / HEAD
πŸ“POST (form types)
↓sent straight away
πŸ™ˆAnswer hidden if not allowed
Preflighted: OPTIONS first
🧾PUT / DELETE
πŸ“¦POST with JSON
🏷️Custom header
↓OPTIONS asks permission
βœ…Real request only if yes
A simple request goes straight out. Anything that could change things in an unusual way gets a preflight first.

The CORS response headers

HeaderMeaning
Access-Control-Allow-OriginWhich origin may read the answer: one exact origin, or * for anyone
Access-Control-Allow-MethodsWhich methods are allowed (used in the preflight answer)
Access-Control-Allow-HeadersWhich request headers are allowed (such as Authorization or Content-Type)
Access-Control-Allow-Credentialstrue means cookies and login data may be included. Then Allow-Origin must be one exact origin, never *
Access-Control-Max-AgeHow long the browser may remember a preflight answer, so it does not ask every time
VisualizerWill the browser send it, and can JavaScript read the answer?Change the page and the API so they are on different origins. Add a JSON POST or a custom header to trigger a preflight, then change what the server answers. Turn on cookies and try Allow-Origin: *. Change SameSite to see when the cookie travels.
Page (where the JavaScript runs)
API it calls
Request
What the API answers
Cookie SameSite
🌐Pagehttps://app.example.com
→↓cross-origin
πŸ–₯️APIrequest ran
→↓response
πŸ™ˆJavaScriptblocked
Cross-origin?
yes
CORS rules apply
Preflight?
no
OPTIONS first
Request sent
yes
reaches the server
Cookie sent
no
credentials off
JS can read
no
the response
The request WAS sent and the server ran it (a POST may have changed data!), but the browser hides the answer from JavaScript: no Access-Control-Allow-Origin header that matches the page. CORS protects the reader, not the server.

Simplified model of the browser rules. The cookie is assumed to belong to the API's host, and the user is logged in. A "site" is scheme plus registrable domain, so a different port is cross-origin but still same-site. Preflight is needed for methods other than GET, HEAD and POST, for custom headers, and for a JSON content type.

07How to Use It / Steps / Implementation

Using cookies and CORS well

  1. 1
    Set safe cookie flags
    Session cookies should be Secure, HttpOnly and SameSite=Lax (or Strict). Use SameSite=None; Secure only when you really need cross-site cookies.
  2. 2
    Keep sessions on the server
    Put a random, hard-to-guess id in the cookie and keep the real data on the server. Give it an expiry and rotate it after login.
  3. 3
    Allow exact origins
    Return the one origin you trust (checked against an allow-list), not a wildcard. Add a Vary: Origin header if the answer depends on it, so caches do not mix answers up.
  4. 4
    List methods and headers
    Answer the preflight with only the methods and headers your API really uses.
  5. 5
    Be careful with credentials
    If you need cookies across origins, set Allow-Credentials: true and name the exact origin. A * is rejected by browsers in that case.
  6. 6
    Cache the preflight
    Set Access-Control-Max-Age to a sensible value, so the browser does not send an OPTIONS before every call.
  7. 7
    Still protect the API
    Check login on the server for every request. Add CSRF protection when you use cookies for login.
A typical CORS answer for a trusted web app
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 600
Vary: Origin
πŸ’‘Avoid CORS when you can
If the page and the API live on the same origin (for example, the API is under /api on the same host, behind a reverse proxy), there is no CORS to configure at all.
⚠️Do not reflect any origin blindly
Copying whatever the request says into Allow-Origin, together with Allow-Credentials, lets any website read your users' private data. Check the origin against an allow-list.

08Key Terms to Know

TermMeaning in easy words
CookieA small piece of data the browser stores for a site and sends back with later requests
Set-CookieThe response header a server uses to create a cookie
Session cookieA cookie with no expiry, removed when the browser closes
HttpOnlyA cookie flag that hides the cookie from JavaScript
SecureA cookie flag that sends it only over HTTPS
SameSiteA cookie flag that limits sending the cookie on cross-site requests (Strict, Lax or None)
OriginScheme + host + port, for example https://app.example.com
Same-origin policyThe browser rule that stops a page from reading data from a different origin
CORSCross-Origin Resource Sharing: headers that let a server allow other origins to read its answers
PreflightAn OPTIONS request the browser sends first, to ask if the real request is allowed
CSRFCross-Site Request Forgery: tricking a logged-in browser into sending an unwanted request

09Pros, Cons and Trade-offs

βœ… Pros
  • Cookies are simple and sent automatically
  • HttpOnly cookies are hidden from scripts
  • CORS gives precise control over who can read what
  • Browser rules protect users by default
  • Preflight results can be cached
⚠️ Cons
  • Cookies are sent automatically, which enables CSRF if you are careless
  • Cross-site cookies are being restricted by browsers
  • CORS errors are confusing and hard to debug
  • Preflight adds an extra round trip
  • CORS does not protect your server from non-browser clients

Trade-offs

ChoiceWe gainWe lose
Cookie for loginAutomatic, HttpOnly, works with plain page loadsNeeds CSRF protection and a server-side session store
Token in a headerNo automatic sending, so no CSRF by defaultJavaScript must store it, which exposes it to XSS
SameSite=StrictStrongest CSRF defenceUsers arriving from other sites look logged out at first
SameSite=NoneWorks in cross-site embedsWeaker CSRF defence and more privacy limits
Allow-Origin: *Easy for public, read-only dataCannot be used with cookies, and exposes the data to every site
Exact origin listSafe and cookies can workMore configuration to maintain
Same-origin proxy (/api)No CORS at allNeeds a reverse proxy in front

10Common Problems and Mistakes

Common mistakes

  1. Treating CORS as security for the API. It only controls browsers. Anyone can call your API with curl, so you still need authentication.
  2. Using * with credentials. The browser rejects it. Developers then "fix" it by reflecting every origin, which is worse.
  3. Forgetting the OPTIONS route. The server returns 404 or 405 to the preflight, and every JSON call fails.
  4. Missing Vary: Origin. A cache stores the answer for one origin and serves it to another.
  5. Session cookie without HttpOnly or Secure. A script injection or a plain-HTTP network can steal it.
  6. No CSRF protection. With cookie login, another site can make the browser send a state-changing request.
  7. Debugging only in the browser console. The real cause is usually in the response headers, so check the Network tab.

Things to watch

πŸͺCookie size
Every cookie is sent with every request to that site. Big cookies slow everything down.
πŸ•΅οΈThird-party cookies
Browsers are blocking or limiting them, so designs that rely on them can break.
πŸ”Redirects
A redirect to another origin during a CORS request can fail in surprising ways.
πŸ§ͺLocal development
localhost:3000 calling localhost:8080 is cross-origin because the ports differ.

11Real-World Examples

πŸ›οΈOnline shops
A session cookie keeps you logged in and remembers your cart as you move around the site.
πŸ“±Web app plus API
A front end on one subdomain calls an API on another. The API returns an exact Allow-Origin and Allow-Credentials.
🏦Banks
Banking sites use Secure, HttpOnly and SameSite cookies, short lifetimes and extra CSRF checks.
🌍Public data APIs
Open data APIs often allow any origin for read-only GET requests, with no cookies.
🧱API gateways
A gateway can add the CORS headers in one place, so each service does not need its own setup.
☁️Object storage
Buckets that serve files to web pages let you set CORS rules on the bucket itself.
πŸ“Note
Browser behaviour around SameSite defaults and third-party cookies keeps changing. Check current browser documentation before depending on a detail.
Mini case: same-origin proxy instead of CORS
🌐Browserapp.example.com
→↓/ and /api
🧱Reverse proxyone origin
→↓/api β†’ API
πŸ–₯️API serviceprivate
Client Proxy Backend
The browser only talks to one origin, so nothing cross-origin happens.

12Related Topics to Read Next

HTTP / HTTPS→

Cookies and CORS are both carried in HTTP headers.

Session vs Token Based Auth→

A cookie often carries the session id or the token.

Authentication vs Authorization→

CORS is neither. It does not log anyone in.

Proxy vs Reverse Proxy→

A reverse proxy can make the page and API one origin.

JWT→

Tokens can live in a cookie or in a header, with different risks.

API Gateway Pattern→

A gateway is a good single place to add CORS headers.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Cookie: data the browser stores and sends back automatically. Set with Set-Cookie.
  • βœ”Flags: Secure + HttpOnly + SameSite (Lax or Strict) for login cookies.
  • βœ”Origin: scheme + host + port. Any difference means cross-origin.
  • βœ”CORS: server headers that let other origins read responses. Enforced by the browser only.
  • βœ”Preflight: OPTIONS first for JSON POST, PUT, DELETE and custom headers.
  • βœ”Credentials: need Allow-Credentials: true and an exact origin. Never *.
  • βœ”Not security: CORS does not stop curl or attackers. Always authenticate on the server.
  • βœ”One line: β€œCookies remember you, CORS decides who may read the answer.”
← Previous
HTTP/1.1 vs HTTP/2 vs HTTP/3
Next β†’
Subnets, CIDR and NAT