CORS and cross-origin setups

Intermediate · 16 min

Why a browser blocks your own API on another port, what a preflight is, how cookies cross origins, and when a dev proxy or one shared origin avoids it all.

Before thisA local environment with Docker ComposeError handling across the stack

LearnThatStack · 16 min

CORS and cross-origin setups

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by LearnThatStackReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An origin is scheme plus host plus port, so a Vite client on port 5173 and an API on port 8787 are different origins even on the same machine.
  • CORS is enforced by the browser, not the server: the server only sends headers saying which origins may read its responses, and curl ignores them entirely.
  • A request with a JSON content type or a custom header triggers a preflight, an OPTIONS request the server must answer before the real request is sent.
  • Sending cookies cross-origin needs credentials on the client and an exact origin plus Access-Control-Allow-Credentials on the server, because a wildcard origin is refused.
  • The simplest fix for cross-origin pain is to avoid it, either with a dev-server proxy or by serving the client and the API from one origin.

The error you will meet on day one

You start the API on port 8787 and the client on port 5173. The first fetch from the page fails with a red console message about CORS. The same request in curl works perfectly. It feels like the server is broken. It isn’t.

The reason is a rule the browser enforces called the same-origin policy. An origin is three things together: scheme, host and port. http://localhost:5173 and http://localhost:8787 share the first two and differ on the third, so they are different origins. By default, a script on one origin may send a request to another but may not read the response. The rule exists because your browser holds cookies for your bank, and a page from any other site must not be able to read your account from it.

CORS (Cross-Origin Resource Sharing) is the opt-in. The server answers each request with headers that say “this origin may read me.” If the headers are absent, the browser throws the response away. The fix therefore lives in the server’s response, and the enforcement lives in the browser, which is why curl does not care. For the HTTP-level detail, see CORS and content negotiation.

The preflight

Some requests are “simple” (a plain GET, or a form-style POST). Anything else triggers a preflight: before sending your request, the browser sends an OPTIONS request asking permission. Sending JSON (Content-Type: application/json) is enough to cause one, and so is a custom header or a method like PATCH.

I ran the Taskboard API (Hono 4.13.20, hono/cors) configured with one allowed origin and checked the preflight by hand:

curl -i -X OPTIONS \
  -H 'Origin: http://localhost:5173' \
  -H 'Access-Control-Request-Method: POST' \
  -H 'Access-Control-Request-Headers: content-type' \
  localhost:8787/api/projects/1/tasks
HTTP/1.1 204 No Content
access-control-allow-credentials: true
access-control-allow-headers: content-type
access-control-allow-methods: GET,HEAD,PUT,POST,DELETE,PATCH,QUERY
access-control-allow-origin: http://localhost:5173
vary: Origin, Access-Control-Request-Headers

The browser reads those headers, decides the real request is allowed, and sends it. Repeating the same preflight with Origin: http://evil.example returned 204 with no access-control-allow-origin line at all. That absence is the refusal: the browser blocks the real request. The server did not return an error. It simply did not grant permission.

Note the vary: Origin header. The server’s answer depends on who asked, so caches must be told. Leave it out and a CDN may hand one origin’s answer to another.

Cookies make it stricter

Taskboard signs people in with a session cookie, so the client must send cookies on cross-origin requests. Two sides have to agree:

// client
fetch("http://localhost:8787/api/me", { credentials: "include" });
// server
cors({ origin: "http://localhost:5173", credentials: true })

With credentials, Access-Control-Allow-Origin: * is rejected by browsers. The server must name the exact origin. That is deliberate: a wildcard plus cookies would let any website make authenticated requests as your user and read the answer.

A cookie also has its own rules about which requests it rides on, separate from CORS. That is the SameSite attribute, which gets its own lesson: CSRF, XSS and cookie settings across layers. The two interact. Note that localhost:5173 and localhost:8787 count as the same site (ports do not matter for site) but different origins, so SameSite=Lax cookies still flow in development, and then break in production if the client and API sit on different registrable domains.

Fix it by not having the problem

CORS is a tax on running two origins. You can often skip it:

  • A dev proxy. Vite can forward /api to the API, so the browser sees one origin. The page calls /api/me, Vite relays it to 8787. From Vite’s configuration docs, a few lines in vite.config.ts do this; I did not run the Vite side here. Nothing cross-origin ever happens, so no preflight and no cookie headaches in development.
  • One origin in production. Put a reverse proxy in front, serving the static client at / and the API at /api. Same origin, same cookies, no CORS configuration to maintain. Deploying the three tiers returns to this layout.
  • Separate origins on purpose. Sometimes you really do want the API on api.taskboard.example, for a mobile app or a public API. Then CORS is the right tool, with an explicit allow-list.

Whichever you choose, keep the list of allowed origins in configuration, not hard-coded. Staging and production differ, and the next group’s environment-variable lesson covers how.

Debugging checklist

When the console says CORS blocked something, check in this order:

  1. Open the network tab. Is there an OPTIONS request? What did it return?
  2. Is the status 2xx? A 404 on OPTIONS means your routing swallowed the preflight.
  3. Does Access-Control-Allow-Origin match the page’s origin exactly, scheme and port included?
  4. If cookies are involved, is Access-Control-Allow-Credentials: true present, and the origin not *?
  5. Does Access-Control-Allow-Headers include every custom header you send?

What the video covers

LearnThatStack’s “Stop Copying CORS Headers - CORS Explained” is about sixteen minutes, published April 2026. Its description says it covers the security reasoning behind CORS, what “origin” precisely means, a two-level protection model, the preflight conversation step by step, what every header does and where each one breaks, and a process for debugging any CORS error. That matches the preflight and credentials parts of this lesson; the proxy and same-origin setups are my own. I could not read a transcript, so I rely on the title and description. Fireship’s two-and-a-half-minute video and Web Dev Simplified’s six-minute one are linked as quick recaps.

Where this fits

The request can now reach the API and the response can be read. What is left is the client code that actually makes the call, with the types and the failures handled. Next: calling the API from the client.

Check yourself

  1. 01Is http://localhost:5173 the same origin as http://localhost:8787?

    No. The origin includes the port, so these differ and the browser applies cross-origin rules to calls between them.

  2. 02Why does a curl request to the API work when the browser's identical request fails?

    CORS is a browser rule. curl does not enforce it, so the missing headers only stop browser scripts from reading the response.

  3. 03What did the preflight for an unlisted origin return in my run?

    A 204 with no Access-Control-Allow-Origin header, so the browser would block the real request.

  4. 04Why can you not use a wildcard origin with credentials?

    Browsers refuse the combination, because it would let any site make authenticated requests, so the server must name the exact origin.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark