← Lessons

quiz vs the machine

Gold1430

Networking

Understanding CORS

Learn why browsers block cross origin requests and how CORS headers permit them.

5 min read · core · beat Gold to climb

The Same Origin Policy

Browsers enforce the same origin policy, which stops a page from reading responses from a different origin, defined by scheme, host, and port. This protects users from one site secretly reading another site's data.

What CORS Adds

Cross Origin Resource Sharing lets a server opt in to sharing with other origins. The server sends response headers that the browser checks before exposing the response to JavaScript.

  • Access Control Allow Origin names which origins may read the response.
  • Access Control Allow Methods lists permitted methods.
  • Access Control Allow Headers lists permitted request headers.
  • Access Control Allow Credentials controls whether cookies may be sent.

The Preflight Request

For requests that are not simple, the browser first sends a preflight using the OPTIONS method to ask permission. Only if the server approves does the real request follow.

Common Pitfalls

CORS is enforced by the browser, not the server, so server to server calls are unaffected. A wildcard origin cannot be combined with credentials, and a missing allow header silently blocks the response even though the server processed the request.

Key idea

CORS lets servers opt out of the same origin policy through response headers, with a preflight check guarding non simple cross origin requests.

Check yourself

Answer to earn rating on the learn ladder.

1. Who enforces CORS rules?

2. What is the purpose of a CORS preflight request?