CodePark/ questions / Fetch, CORS & HTTP versions
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Fetch, CORS & HTTP versions

What is CORS? Explain simple requests, preflight requests and how credentials work.

CORS (Cross-Origin Resource Sharing) lets a server allow other origins to read its responses. An origin is the scheme, domain and port, like https://shop.com.

By default, the same-origin policy stops scripts from reading responses from another origin. With CORS, the server opts in with response headers like Access-Control-Allow-Origin.

Simple requests. A request is "simple" when all three of these are true:

  • The method is GET, HEAD or POST.
  • It uses only basic headers, with no custom ones.
  • Its content type is form data or plain text.

The browser sends a simple request directly. Then it checks the response headers before it lets the script see the response.

Preflight requests. All other requests are preflighted. Examples are PUT, DELETE, custom headers like Authorization, or Content-Type: application/json. First the browser sends an OPTIONS request to ask permission. The server must reply with Access-Control-Allow-Methods and Access-Control-Allow-Headers. Access-Control-Max-Age lets the browser cache this answer.

Credentials. To send cookies, the client sets credentials: "include". The server must return Access-Control-Allow-Credentials: true with an explicit origin, not *.

The browser enforces CORS, not the server.

  • The same-origin policy blocks reading other origins, and the server opts in with CORS headers.
  • Simple requests go straight through, and the browser checks the response headers.
  • Other methods, custom headers or JSON trigger a preflight OPTIONS request.
  • Credentials need Access-Control-Allow-Credentials and an explicit origin, not *.
  • The browser enforces CORS, not the server.