CORS: what it protects and how to configure it

API design: REST, HTTP, GraphQL and gRPC Junior Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Pick the fix

The SPA at https://app.example.com sends cookies to the API. Which CORS config is right?

Options
Hint 1 of 1

Credentials need an explicit origin.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Allow-Origin: https://app.example.com, Allow-Credentials: true, Vary: Origin

Correct. One explicit origin with credentials; Vary keeps caches honest.

With credentials, the browser only shares the response if Allow-Origin names the exact calling origin and Allow-Credentials is true. Vary: Origin stops a cache handing one origin's answer to another.

Why not the others?
  • B Allow-Origin: *, Allow-Credentials: true. Browsers reject this combination.
  • C Echo whatever Origin arrives, with credentials. Any website could read your users' data.
  • D Disable CORS on the server. There's nothing to disable; without headers the browser blocks reads.

30-second answer

Browsers block a page from reading responses from another origin unless that server opts in. CORS is the opt-in: the API sends Access-Control-Allow-Origin for the allowed origin; for non-simple requests (custom headers, JSON bodies, PUT/DELETE) the browser first sends an OPTIONS preflight and checks Allow-Methods and Allow-Headers. Allow your known front-end origins explicitly. CORS doesn't protect the API from non-browser clients.

Practise saying it · 30 s. No recording, just a timer

Explain CORS.

Say your answer out loud, then check which of these points you covered:

  • Browser same-origin rule
  • Server opts in with headers
  • Preflight for non-simple
  • No * with credentials
  • Not CSRF protection

Deep dive

Access-Control-Allow-Origin: * can't be combined with credentials (cookies).

Reflecting any Origin header back with credentials allowed lets any site read users' data.

Cache preflights with Access-Control-Max-Age.

CSRF is a separate problem: CORS controls reading responses, not whether a simple request is sent.

Common mistakes

  • Echoing the request's Origin back for everyone with Allow-Credentials: true.
  • Thinking CORS is server-side security against curl.
  • Forgetting to handle OPTIONS, so preflights fail.

Senior take & follow-ups

Explain same-origin, the opt-in headers, preflight, and the credentials pitfall.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why does a JSON POST trigger a preflight?

    Show hint

    Content-Type application/json isn't a 'simple' type.

  2. Does CORS stop CSRF?

    Show hint

    No; use SameSite cookies or CSRF tokens.

Suggest a fix if something here is wrong or out of date.