CORS

CORS is a set of HTTP headers that lets a server share its responses with other origins. With the right headers, a script on another origin can read the response of a fetch() call.

Concept

Also called Cross-Origin Resource Sharing

Updated

On this page

How it works

Browsers stop scripts from reading responses from other origins. This applies to fetch() and XMLHttpRequest. With CORS, the server opts in. It sends Access-Control-Allow-Origin with the origin of the page, or * for any origin when the request has no credentials.

Some requests are more than a simple form can send, for example a PUT or a custom header. For these, the browser first sends a preflight request with the OPTIONS method. The server answers with the methods and headers it accepts. Then the browser sends the real request.

CORS and iframes

CORS headers do not decide if a page can load in an iframe. The framed page controls that with Content-Security-Policy: frame-ancestors or X-Frame-Options. CORS controls only what scripts can read.

When a CORS check fails, the script gets only a general error. The browser console shows the reason.

Example

HTTP
# Request from a script on https://example.com
Origin: https://example.com

# Response from https://api.example.com
Access-Control-Allow-Origin: https://example.com

The browser gives the response to the script only when the origin in the response matches.

How to set it

Send Access-Control-Allow-Origin with the origin that may read the response. Add the other headers only when you need them.

Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type

With credentials, such as cookies, the browser does not accept "*". Name the exact origin.

Learn more

Sources

Know before you embed.

Free, no sign-up, nothing stored. Paste a URL and get a verdict, a live preview, and the fix.