Internet Frontend 05 ๐ Same-Origin Policy and CORS
The Same-Origin Policy is a browser security boundary that prevents a script loaded from one origin from reading the resources of another origin. CORS is the mechanism that lets a server relax that boundary. It is not a browser feature that grants access; it is a protocol that the server uses to declare which other origins are allowed to read its responses. The browser enforces the policy, and the server declares the exceptions. The two must agree, and when they do not, the browser blocks the response even though the server sent it .
The origin is the combination of the scheme, the host, and the port. https://example.com and http://example.com are different origins because the schemes differ. https://example.com and https://example.com:8443 are different origins because the ports differ. https://example.com and https://api.example.com are different origins because the hosts differ. The policy is strict, and the strictness is the reason a frontend that calls an API on a different port is a frontend that needs CORS.
Key point: CORS is a server-side declaration that a browser enforces. The server sends the Access-Control-Allow-Origin header, and the browser checks it before exposing the response to the calling script. A simple request is sent directly, and the browser checks the response headers. A preflighted request is sent as an OPTIONS request first, and the browser checks the preflight response before sending the actual request .
Why the Same-Origin Policy exists
The credential problem. A browser stores cookies, localStorage, and session tokens for the origins the user has visited. Without the Same-Origin Policy, a script from evil.com could read the user’s bank statement from bank.com by making a request with the user’s cookies. The policy is the barrier that prevents the cross-origin read. The cookie is still sent with the requestโthe policy does not block the requestโbut the response is not exposed to the calling script .
The CSRF problem. The policy blocks the cross-origin read, not the cross-origin write. A form on evil.com can submit a POST to bank.com, and the browser sends the request with the user’s cookies. The policy prevents evil.com from reading the response, but the request itself has already been sent. The CSRF token is the mechanism that compensates for the policy’s read-only scope. The SameSite cookie attribute is the second mechanism, and it restricts the cookies that are sent on the cross-site requests.
The CORS relaxation. CORS is the server’s declaration that a specific origin is allowed to read the response. The Access-Control-Allow-Origin header names the origin, and the browser exposes the response to the script only if the header matches the calling origin. The Access-Control-Allow-Credentials header is the second declaration, and it allows the cookies to be sent with the cross-origin request. The two headers are the server’s side of the contract, and the browser is the enforcer .
The trade-off. The policy is strict by default, and the strictness is the reason the frontend and the backend must agree on the CORS configuration. A wildcard Access-Control-Allow-Origin: * allows any origin to read the response, but it is incompatible with the credentials. A specific origin allows the credentials, but it must be one of the origins the server knows about. The choice is the trade-off between the convenience and the security.
a. The simple request and the preflighted request
A request is “simple” if it uses one of the GET, HEAD, or POST methods, and if the Content-Type is one of application/x-www-form-urlencoded, multipart/form-data, or text/plain, and if it does not set any custom headers. A simple request is sent directly, and the browser checks the response headers before exposing the response to the script .
GET /api/data HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Content-Type: application/json
The browser compares the Origin header with the Access-Control-Allow-Origin header. If they match, the response is exposed. If they do not, the browser blocks the response, and the script sees a CORS error. The request itself was sent, and the server processed it. The browser’s block is the read barrier, not the write barrier .
A request is “preflighted” if it uses a method other than the simple methods, or if it sets a custom header, or if the Content-Type is application/json. The browser sends an OPTIONS request first, and the server responds with the allowed methods and headers .
OPTIONS /api/data HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type, X-Custom-Header
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, X-Custom-Header
Access-Control-Max-Age: 86400
The preflight response declares the methods and the headers that the server allows. The Access-Control-Max-Age header is the cache duration for the preflight response, and it is the mechanism that avoids a preflight on every request. The browser sends the actual PUT request only if the preflight response allows it .
b. The credentials and the wildcard
The Access-Control-Allow-Credentials: true header is the server’s declaration that the cookies and the HTTP authentication are allowed on the cross-origin request. The header is incompatible with the wildcard origin, because the wildcard would allow any origin to read the credentialed response .
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Set-Cookie: session=abc123; SameSite=None; Secure
The SameSite=None attribute is required for the cookie to be sent on the cross-origin request, and the Secure attribute is required when SameSite=None is set. The three piecesโthe Access-Control-Allow-Credentials header, the SameSite=None attribute, and the Secure attributeโare the contract for the credentialed CORS .
The wildcard origin is the simpler configuration, but it is only for the public endpoints that do not need the credentials.
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
The wildcard is the declaration that any origin can read the response. It is the correct configuration for a public CDN or a public API, and it is the wrong configuration for an endpoint that uses cookies .
Complete Example Session
// ============================================
// PART 1: THE ORIGIN
// ============================================
// The origin is scheme + host + port.
// https://app.example.com
// https://api.example.com โ different origin
// http://app.example.com โ different origin
// https://app.example.com:8443 โ different origin
// ============================================
// PART 2: THE SIMPLE REQUEST
// ============================================
// GET /api/data with no custom headers.
// The browser sends the Origin header.
// The server responds with Access-Control-Allow-Origin.
// The browser checks the header before exposing the response.
// ============================================
// PART 3: THE PREFLIGHT
// ============================================
// PUT /api/data with a JSON body.
// The browser sends an OPTIONS request first.
// The server responds with the allowed methods and headers.
// The browser sends the actual PUT request.
// ============================================
// PART 4: THE PREFLIGHT CACHE
// ============================================
// Access-Control-Max-Age: 86400
// The preflight response is cached for 24 hours.
// The browser does not send a preflight for every request.
// ============================================
// PART 5: THE CREDENTIALS
// ============================================
// Access-Control-Allow-Credentials: true
// Set-Cookie: session=abc123; SameSite=None; Secure
// The credentials are allowed.
// The wildcard origin is not allowed with the credentials.
// ============================================
// PART 6: THE WILDCARD
// ============================================
// Access-Control-Allow-Origin: *
// Any origin can read the response.
// The credentials are not allowed with the wildcard.
// ============================================
// PART 7: THE ERROR
// ============================================
// The browser blocks the response if the Origin
// does not match the Access-Control-Allow-Origin.
// The error is a CORS error in the console.
// The request was sent; the response was not exposed.
// ============================================
// PART 8: THE SERVER CONFIGURATION
// ============================================
// The Express configuration:
import cors from 'cors';
app.use(cors({
origin: 'https://app.example.com',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'X-Custom-Header'],
maxAge: 86400,
}));
// ============================================
// PART 9: THE VERIFICATION
// ============================================
// The browser's network tab shows the preflight request.
// The "CORS" filter shows the CORS errors.
// The response headers show the Access-Control-* headers.
// ============================================
// PART 10: THE CHECKLIST
// ============================================
// [ ] The allowed origin is explicit, not a wildcard, if credentials are used.
// [ ] The Access-Control-Allow-Credentials is set if cookies are sent.
// [ ] The SameSite=None and Secure attributes are set on the cookie.
// [ ] The Access-Control-Max-Age is set to avoid the preflight on every request.
// [ ] The allowed methods and headers are explicit.
// [ ] The CORS error is checked in the browser console.
The ten parts covered the origin, the simple request, the preflight, the preflight cache, the credentials, the wildcard, the error, the server configuration, the verification, and the checklist. The through-line is that CORS is a server-side declaration that the browser enforces.
Quick Reference
The CORS headers
| Header | Direction | Purpose |
|---|---|---|
Origin | Request | The calling origin |
Access-Control-Allow-Origin | Response | The allowed origin |
Access-Control-Allow-Methods | Preflight response | The allowed methods |
Access-Control-Allow-Headers | Preflight response | The allowed headers |
Access-Control-Allow-Credentials | Response | The cookie allowance |
Access-Control-Max-Age | Preflight response | The preflight cache duration |
The simple vs preflighted request
| Aspect | Simple | Preflighted |
|---|---|---|
| Methods | GET, HEAD, POST | Everything else |
| Content-Type | text/plain, multipart/form-data, application/x-www-form-urlencoded | application/json |
| Custom headers | No | Yes |
| Preflight | No | Yes (OPTIONS) |
The credentials
| Configuration | Cookie sent | Wildcard allowed |
|---|---|---|
Access-Control-Allow-Credentials: true | Yes | No |
| No credentials header | No | Yes |
SameSite=None; Secure | Yes (cross-site) | No |
Best Practices
โ Do This:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
// The Express CORS configuration
app.use(cors({ origin: 'https://app.example.com', credentials: true }));
โ Don’t Do This:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
// The wildcard with the credentials
app.use(cors({ origin: '*', credentials: true })); // invalid
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| The CORS error persists | The origin is not in the allow list | Add the origin to the server config |
| The cookie is not sent | The SameSite attribute is not None | Set SameSite=None; Secure |
| The preflight fails | The method or header is not allowed | Add the method and header to the preflight response |
| The preflight is sent on every request | Access-Control-Max-Age is not set | Set the cache duration |
| The wildcard origin with credentials | The two are incompatible | Use an explicit origin |
Summary
| Item | Value |
|---|---|
| Origin | Scheme + host + port |
| Simple request | GET, HEAD, POST with the simple content types |
| Preflighted request | OPTIONS first, then the actual request |
| Allow origin | Access-Control-Allow-Origin |
| Allow credentials | Access-Control-Allow-Credentials: true |
| Preflight cache | Access-Control-Max-Age |
| Wildcard | *, incompatible with credentials |
Key takeaways:
- The Same-Origin Policy is a read barrier. It blocks the cross-origin read, not the cross-origin write. The request is sent, and the response is not exposed to the calling script. The CSRF token and the
SameSiteattribute are the mechanisms that compensate for the write path . - CORS is the server’s declaration. The server sends the
Access-Control-Allow-Originheader, and the browser checks it before exposing the response. The header must match the calling origin, or the browser blocks the response . - The preflight is the mechanism for the non-simple requests. The browser sends an
OPTIONSrequest first, and the server declares the allowed methods and headers. TheAccess-Control-Max-Ageheader caches the preflight response . - The credentials and the wildcard are incompatible. The
Access-Control-Allow-Credentials: trueheader requires an explicit origin, not a wildcard. TheSameSite=NoneandSecureattributes are the cookie-side contract . - The request is sent; the response is blocked. The browser does not prevent the request from reaching the server. It prevents the calling script from reading the response. The distinction matters for the CSRF risk, where the write is the attack and the read is the blocked part .
Remember: CORS is a server-side declaration that the browser enforces. The origin is the scheme, the host, and the port, and the policy is strict about all three. The simple request is sent directly, and the preflighted request is sent after an OPTIONS exchange. The Access-Control-Allow-Origin header is the server’s side of the contract, and the browser is the enforcer. The wildcard is for the public endpoints, and the explicit origin is for the credentialed ones. The two are not interchangeable.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!