Belajar
← All lessons

How CORS works

Call another origin's API

app.test page
Browser
api.test

page.js

// running on https://app.testtry {  const res = await fetch("https://api.test/me");  const user = await res.json();} catch (err) {  // TypeError: Failed to fetch}

server.js

// running on https://api.testapp.get("/me", (req, res) => {  // req.headers.origin is "https://app.test"  res.set("Access-Control-Allow-Origin", "https://app.test");  res.json({ name: "Ana", plan: "pro" });});

inside the browser

// built into the browser, for every cross-origin responseconst allowed = res.headers.get("Access-Control-Allow-Origin");if (allowed !== "*" && allowed !== page.origin) {  throw new TypeError("Failed to fetch");}return res; // now the page can read it

Same origin means same scheme, host and port

This page is https://app.test. Call this URL:
Try
Your URL, split up

A subdomain like api.app.test is a different host, so it's a different origin

origin.js

// an origin is scheme + host + port. The path doesn't countfunction sameOrigin(a, b) {  const x = new URL(a);  const y = new URL(b);  return x.protocol === y.protocol    && x.hostname === y.hostname    && x.port === y.port;}// new URL() turns a default port (443, 80) into ""

Some requests ask first with an OPTIONS preflight

Browser
api.test

page.js

// running on https://app.testawait fetch("https://api.test/notes/1", {  method: "PUT",  headers: { "Content-Type": "application/json" },  body: JSON.stringify({ text: "hi" }),});

server.js

app.options("/notes/:id", (req, res) => {  res.set("Access-Control-Allow-Origin", "https://app.test");  res.set("Access-Control-Allow-Methods", "GET, PUT");  res.set("Access-Control-Allow-Headers", "Content-Type");  res.status(204).end();}); app.put("/notes/:id", (req, res) => {  res.set("Access-Control-Allow-Origin", "https://app.test");  res.json(save(req.params.id, req.body));});

Cookies need an exact origin and an explicit yes

fetch credentialsomitincludeAllow-Origin*https://app.testAllow-Credentialsnot senttrue
Request
Response

Don't copy the Origin header back blindly. Check it against a list first

page.js

// cookies stay home unless you ask for themawait fetch("https://api.test/me", {  credentials: "include",});

server.js

// * is not allowed once cookies are involvedres.set("Access-Control-Allow-Origin", "https://app.test");res.set("Access-Control-Allow-Credentials", "true");

Topics

Next: How cookies and sessions work

Open lesson