A browser does not let a script on a page read responses from another domain, port or scheme — this protects users’ data. CORS, defined in the Fetch standard, is a way to relax that restriction: the server lists whose requests are allowed, and the browser enforces it.
How it works
For a cross-origin request the browser adds an Origin header with the page’s scheme, domain and port. The server replies with an Access-Control-Allow-Origin header: either * or a specific origin. If permission is missing or does not match, the browser does not let the script read the response.
| Header | Sent by | Purpose |
|---|---|---|
Origin | browser | the page’s origin; present in every CORS request |
Access-Control-Allow-Origin | server | the allowed origin, or * |
Access-Control-Allow-Methods, Allow-Headers | server | the permitted request methods and headers |
Access-Control-Allow-Credentials | server | allows requests with cookies; * cannot then be used |
Access-Control-Expose-Headers | server | which response headers the script may read |
Access-Control-Max-Age | server | how many seconds to cache the response to a preflight request |
Preflight request
Before a request that could change data, the browser first asks for permission by sending OPTIONS — a preflight request. It is needed for methods other than GET, HEAD and POST, for non-standard headers, and for a Content-Type other than application/x-www-form-urlencoded, multipart/form-data and text/plain.
OPTIONS /api/profile HTTP/1.1Origin: https://app.example.comAccess-Control-Request-Method: PUTAccess-Control-Request-Headers: Content-Type HTTP/1.1 204 No ContentAccess-Control-Allow-Origin: https://app.example.comAccess-Control-Allow-Methods: PUT, DELETEAccess-Control-Allow-Headers: Content-TypeAccess-Control-Max-Age: 86400If the server allows it, the browser sends the actual request. Access-Control-Max-Age sets how many seconds to remember the permitted methods and headers; the default is 5 seconds, and the example above uses 86400 (one day), but every browser has its own upper limit.
What to keep in mind
- The browser enforces CORS, not the server:
curland server-side clients make the same requests freely, so it is a rule for page scripts, not protection of the server against attacks. - With
Access-Control-Allow-Credentials: trueyou cannot use*: an exact origin is required, otherwise the browser rejects the response. - The browser sends simple requests without a preflight — an HTML form could send the same, so the server defends against such requests with CSRF protection.
- A CORS error in the browser console most often means the server did not send the permission; the fix is a server setting or a reverse proxy on your own domain.
Sources
the term is written from these pagesVerified 9 Nov