Same-Origin Policy and CORS

A web page may call an API on a different origin. The browser has rules about which responses JavaScript may read. The API still decides who may use the data.

On this page

Compare two origins

An origin consists of scheme, host, and port. A different path can share an origin. Changing the subdomain or port changes the origin. By default, the same-origin policy restricts a script from reading many cross-origin responses.

const app = new URL("https://app.example/documents");
new URL("/settings", app).origin === app.origin;          // true
new URL("https://api.example").origin === app.origin;     // false

Share a response with an approved frontend

For cookie-authenticated cross-origin fetches, the client needs credentials set to include and applicable cookies. Return the exact approved origin and allow credentials. If the header varies by Origin, use Vary. For requests requiring preflight, the API also answers OPTIONS with the allowed method and headers. CORS governs browser reads and some request dispatch. Every endpoint needs its own access checks.

Access-Control-Allow-Origin: https://app.example
Access-Control-Allow-Credentials: true
Vary: Origin

Official references