| |

Internet Frontend 05 ๐ŸŒ Same-Origin Policy and CORS

โฑ๏ธ Estimated read: 10 min | |

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

HeaderDirectionPurpose
OriginRequestThe calling origin
Access-Control-Allow-OriginResponseThe allowed origin
Access-Control-Allow-MethodsPreflight responseThe allowed methods
Access-Control-Allow-HeadersPreflight responseThe allowed headers
Access-Control-Allow-CredentialsResponseThe cookie allowance
Access-Control-Max-AgePreflight responseThe preflight cache duration

The simple vs preflighted request

AspectSimplePreflighted
MethodsGET, HEAD, POSTEverything else
Content-Typetext/plain, multipart/form-data, application/x-www-form-urlencodedapplication/json
Custom headersNoYes
PreflightNoYes (OPTIONS)

The credentials

ConfigurationCookie sentWildcard allowed
Access-Control-Allow-Credentials: trueYesNo
No credentials headerNoYes
SameSite=None; SecureYes (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

PitfallWhy It HappensFix
The CORS error persistsThe origin is not in the allow listAdd the origin to the server config
The cookie is not sentThe SameSite attribute is not NoneSet SameSite=None; Secure
The preflight failsThe method or header is not allowedAdd the method and header to the preflight response
The preflight is sent on every requestAccess-Control-Max-Age is not setSet the cache duration
The wildcard origin with credentialsThe two are incompatibleUse an explicit origin

Summary

ItemValue
OriginScheme + host + port
Simple requestGET, HEAD, POST with the simple content types
Preflighted requestOPTIONS first, then the actual request
Allow originAccess-Control-Allow-Origin
Allow credentialsAccess-Control-Allow-Credentials: true
Preflight cacheAccess-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 SameSite attribute are the mechanisms that compensate for the write path .
  • CORS is the server’s declaration. The server sends the Access-Control-Allow-Origin header, 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 OPTIONS request first, and the server declares the allowed methods and headers. The Access-Control-Max-Age header caches the preflight response .
  • The credentials and the wildcard are incompatible. The Access-Control-Allow-Credentials: true header requires an explicit origin, not a wildcard. The SameSite=None and Secure attributes 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.

Was this helpful?


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!