Skip to lesson

Same-origin policy and CORS (the idea)

ShopLite's store page runs at one address and its API at another. The page's script asks the API for products, the API answers, and yet the browser refuses to give the data to the script. Why does it do that?

An origin is scheme + host + port

An origin is the scheme (http or https), the host and the port of a URL. Two URLs have the same origin only when all three match exactly.

Compare URLs with the page address one part at a time and decide which ones share its origin.

Example 1 · Same origin or not?

Text
Page origin: https://shop.example.com1. https://shop.example.com/api/products?page=22. http://shop.example.com/api/products3. https://api.example.com/products4. https://shop.example.com:8443/api/products5. https://shop.example.com:443/cart6. http://localhost:5173 compared with http://127.0.0.1:5173
Answer
1. same origin   (path and query do not count)
2. cross-origin  (scheme is http, not https)
3. cross-origin  (host is api.example.com)
4. cross-origin  (port 8443, not the default 443)
5. same origin   (443 is the default port for https)
6. cross-origin  (different host names, even though both reach this computer)

What this code does

  • Compare scheme, host and port one by one; the first difference makes it cross-origin. A subdomain such as api.example.com is a different host.
  • Case 6 surprises many developers: localhost and 127.0.0.1 reach the same computer, but the browser compares the names as text.

The path, the query string and the fragment do not matter. When a URL leaves out the port, the default is used: 80 for http and 443 for https. So https://shop.example.com and https://shop.example.com:443 are the same origin, but the http:// and https:// versions of one site are not.

Predict the output

Same origin or cross-origin?

The page is at https://shop.example.com. Pick the verdict for the URL it calls.

Round 1 of 3

The page calls this URL.

Page: https://shop.example.com
Calls: https://shop.example.com/products?sort=price#reviews

What the browser blocks, and why

The same-origin policy is a browser rule: a script may send a request to another origin, but may not read the response unless that origin allows it.

Call the API from a page on another port and watch the browser refuse to hand the data to the script.

Example 2 · The browser blocks a cross-origin read

Runs in: Chrome with the demo front end on localhost:5173 and the demo API on localhost:8080

Text
Page:    http://localhost:5173   (the front end, during development)Script:  fetch('http://localhost:8080/api/products')API:     sends no CORS headers yet
Sample output (Chrome console)
Access to fetch at 'http://localhost:8080/api/products' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Failed to load resource: net::ERR_FAILED
Uncaught (in promise) TypeError: Failed to fetch
    at http://localhost:5173/:3:1

What this code does

  • Port 5173 and port 8080 are different origins, so the browser looked for permission in the response. There was none, and the script got TypeError: Failed to fetch instead of the data.
  • The request did reach the API, and the API answered 200 (Example 3 shows the same answer with curl). The browser only refused to give the body to the script, and the Network tab marks the row as CORS error. Firefox and Safari word the message differently, but name the same header.

Browsers attach your cookies to requests for a site, even when a script on another site starts the request. Without this rule, a page on evil.example could call https://bank.example/api/balance with your bank cookie and read your balance.

The request is still sent and the server still answers; only the read is blocked. That is why the CSRF defences from the Sessions lesson are still needed.

CORS: the server opts in with Access-Control-Allow-Origin

CORS (Cross-Origin Resource Sharing) is a set of response headers with which a server tells the browser which other origins may read its responses.

Ask the API as the front end on port 5173 would, and see which origins get a permission header.

Example 3 · The API allows one origin

Runs in: the demo server on localhost:8080

Terminal
curl -i -H "Origin: http://localhost:5173" http://localhost:8080/api/productscurl -i -H "Origin: https://evil.example" http://localhost:8080/api/products
Sample output
$ curl -i -H "Origin: http://localhost:5173" http://localhost:8080/api/products
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 98
Connection: close
Date: Fri, 16 Oct 2026 02:55:21 GMT
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin

[{"id":1,"name":"Java notebook","price":"120.00"},{"id":2,"name":"USB-C cable","price":"249.00"}]

$ curl -i -H "Origin: https://evil.example" http://localhost:8080/api/products
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 98
Connection: close
Date: Fri, 16 Oct 2026 02:55:21 GMT

[{"id":1,"name":"Java notebook","price":"120.00"},{"id":2,"name":"USB-C cable","price":"249.00"}]

What this code does

  • -H "Origin: ..." makes curl send the header a browser would add. For the allowed front end, the API answers Access-Control-Allow-Origin: http://localhost:5173 and Vary: Origin, so a browser would now hand the data to the script.
  • For https://evil.example the API still returns the data, but without the permission header. A browser would block the read; curl just prints it, because curl does not enforce CORS.

On a cross-origin request the browser adds an Origin header, such as Origin: http://localhost:5173. If the response carries Access-Control-Allow-Origin: http://localhost:5173 (or * for public data), the browser lets the script read it. In development the front end and the API often sit on different ports, so the API must allow the front end's origin.

For anything behind a login:

  • Allow a list of exact origins, not every origin.
  • Send Vary: Origin when the answer depends on the Origin header, so caches do not mix up answers for different sites.
  • To send cookies cross-origin, the script must ask for it (credentials: 'include' in fetch) and the response must have Access-Control-Allow-Credentials: true with an exact origin, never *.

Fix the error

Fix the CORS error

The browser blocks the response. Pick the header line that fixes it.

Round 1 of 2

The front end runs at http://localhost:5173. Fix the permission header.

HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin

Error

Access to fetch at 'http://localhost:8080/api/products' from origin 'http://localhost:5173' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000' that is not equal to the supplied origin.

Preflight OPTIONS requests

A preflight is an OPTIONS request that the browser sends by itself before the real request, asking whether the server accepts that origin, method and headers.

Send the preflight a browser would send before a JSON POST and read the permission headers in the answer.

A CORS preflight, in four steps. The browser sends OPTIONS /api/orders with an Origin header and the request method POST. The API answers 204 with Access-Control-Allow-Origin and Access-Control-Allow-Methods. Because that allows it, the browser sends the real POST /api/orders.

Example 4 · A preflight for a JSON POST

Runs in: the demo server on localhost:8080

Terminal
curl -i -X OPTIONS -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: content-type" http://localhost:8080/api/orders
Sample output
HTTP/1.1 204 No Content
Connection: close
Date: Fri, 16 Oct 2026 02:55:22 GMT
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600

What this code does

  • This is the OPTIONS request a browser sends before POST /api/orders with a JSON body. The 204 answer allows the origin, the methods GET, POST, PUT, DELETE and the headers Content-Type, Authorization.
  • Access-Control-Max-Age: 600 lets the browser remember this answer for 10 minutes, so it does not send a preflight before every call. In the Network tab you see the OPTIONS row and then the POST row.

The preflight carries Origin, Access-Control-Request-Method and Access-Control-Request-Headers. The real request is sent only if the answer allows that origin, method and headers.

Simple requests skip the preflight: GET, HEAD or POST with only basic headers and a form or plain-text body. Almost every API call needs one, because sending JSON (Content-Type: application/json), an Authorization header, or PUT, PATCH or DELETE all trigger it.

Order of execution

Put the preflight in order

Tap the steps in the order they happen.

Reading a CORS error, and why curl and Postman never see it

Read a preflight failure the way the browser Console shows it, then repeat the request from curl.

Example 5 · Reading a preflight failure in the console

Runs in: Chrome with the demo front end on localhost:5173 and the demo API on localhost:8080

Text
Page:    http://127.0.0.1:5173/order.htmlScript:  fetch('http://localhost:8080/api/orders', {           method: 'POST',           headers: { 'Content-Type': 'application/json' },           body: '{"items":["Java notebook"]}' })API:     allows only http://localhost:5173
Sample output (Chrome console)
Access to fetch at 'http://localhost:8080/api/orders' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Failed to load resource: net::ERR_FAILED
Uncaught (in promise) TypeError: Failed to fetch
    at http://127.0.0.1:5173/order.html:3:1

What this code does

  • Read it in three parts. URL: /api/orders. Origin: http://127.0.0.1:5173, opened by IP address instead of localhost. Reason: the preflight answer had no Access-Control-Allow-Origin for this origin.
  • Because the preflight failed, the browser never sent the POST, so no order was placed. The fix is on the API: add http://127.0.0.1:5173 to the allowed origins, or open the page as localhost:5173.

Example 6 · The same request from curl works

Runs in: the demo server on localhost:8080

Terminal
curl -i -X OPTIONS -H "Origin: http://127.0.0.1:5173" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: content-type" http://localhost:8080/api/orderscurl -i -H "Origin: http://127.0.0.1:5173" -H "Content-Type: application/json" -d @order.json http://localhost:8080/api/orders
Sample output
$ curl -i -X OPTIONS -H "Origin: http://127.0.0.1:5173" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: content-type" http://localhost:8080/api/orders
HTTP/1.1 204 No Content
Connection: close
Date: Fri, 16 Oct 2026 02:55:23 GMT


$ curl -i -H "Origin: http://127.0.0.1:5173" -H "Content-Type: application/json" -d @order.json http://localhost:8080/api/orders
HTTP/1.1 201 Created
Content-Type: application/json
Content-Length: 60
Connection: close
Date: Fri, 16 Oct 2026 02:55:23 GMT

{"orderId":501,"status":"PLACED","items":["Java notebook"]}

What this code does

  • The preflight answer really lacks the Access-Control-* headers for this origin, which confirms the console message. order.json holds {"items":["Java notebook"]}.
  • curl then sends the POST and gets 201 Created, because curl never checks CORS. "It works in Postman" therefore says nothing about CORS: test CORS fixes in the browser.

A CORS error appears in the browser Console as "blocked by CORS policy", followed by the reason. Read three things: the URL called, the page's origin, and the reason after the colon. The reason names the header that is missing or wrong, so the fix is always on the server.

CORS is enforced only by browsers. curl, Postman and server-to-server calls ignore it, so the same request works there. That is not a bug: CORS protects users of a browser from other websites. It is not a lock on your API, which still needs its own authentication.

Next step

Check your understanding

12 quick questions