Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท API Security

CORS and Security Headers

Understand the same-origin policy, CORS preflight requests and credentials, then set the security headers and cookie flags every REST API should send.

Your API works in Postman and in curl, but the browser console shows "blocked by CORS policy". Nearly every web developer meets this error. It is not a bug in your server and not a firewall. It is the browser enforcing the same-origin policy, and your server has to opt in to allow other websites to read its responses.

This lesson explains what an origin is, how CORS works (including preflight requests), the mistakes that make it unsafe, and the security headers and cookie flags that complete the picture. Because CORS is enforced by browsers, the demos build the server side and test it by sending the headers a browser would send.

What CORS is

Origin scheme + host + port.
Same-origin policy Pages cannot read other origins by default.
CORS The server says who may read.

CORS relaxes a browser rule. It is not authentication.

1 / 2

What is an origin?

An origin is the triple scheme + host + port. Two URLs have the same origin only if all three match.

URL Same origin as https://app.example.com?
https://app.example.com/page Yes
http://app.example.com No (scheme)
https://api.example.com No (host)
https://app.example.com:8443 No (port)

A page on https://app.example.com can call its own origin freely. To call https://api.example.com, the browser sends the request but only lets the page read the response if the API answers with a matching Access-Control-Allow-Origin header.

Simple requests and preflight

For simple requests (GET, HEAD or POST with a basic content type and no custom headers) the browser sends the request with an Origin header and checks the response headers afterwards.

Everything else, such as PUT, DELETE, JSON bodies with Content-Type: application/json, or an Authorization header, first triggers a preflight: an automatic OPTIONS request that asks permission.

sequenceDiagram
    participant B as Browser (app.example.com)
    participant A as API (api.example.com)
    B->>A: OPTIONS /notes (Origin, Access-Control-Request-Method: PUT, Request-Headers: authorization)
    A->>B: 204 + Allow-Origin, Allow-Methods, Allow-Headers, Max-Age
    B->>A: PUT /notes/1 (Origin, Authorization)
    A->>B: 200 + Allow-Origin
    Note over B: JavaScript may read the response

The real request is sent only if the preflight answer allows it.

The CORS response headers

Header Meaning
Access-Control-Allow-Origin The origin allowed to read the response (one origin, or *)
Access-Control-Allow-Methods Methods allowed (preflight response)
Access-Control-Allow-Headers Request headers allowed (preflight response)
Access-Control-Allow-Credentials true lets the page send cookies or HTTP auth
Access-Control-Max-Age Seconds the browser may cache the preflight answer
Access-Control-Expose-Headers Response headers JavaScript may read (beyond the basic ones)
Vary: Origin Tells caches the response depends on the Origin header

A correct CORS handler

The safe approach is an allowlist: compare the request's Origin with a list of known origins and echo it back only if it matches. Add Vary: Origin so shared caches do not serve a response meant for one origin to another.

Node.js CORS allowlist and preflight

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the last two rows. For the unknown site the server still answers 200. It is the browser that refuses to hand the response to the page when the allow-origin header is missing. For a request with no Origin header at all (curl, a mobile app, another server), CORS does not apply.

Common CORS mistakes

  1. Reflecting any origin with credentials. Copying the Origin header into Allow-Origin without a check, plus Allow-Credentials: true, lets any website read logged-in users' data.
  2. Using * with credentials. Browsers refuse it: with cookies you must name the exact origin.
  3. Trusting a regex like /example\.com$/ that also matches evilexample.com. Compare full origins exactly.
  4. Thinking CORS is security for the API. It restricts which websites can read responses in a browser. Attackers use scripts, not browsers, so authentication and authorization are still required.
  5. Forgetting preflight for errors: a 401 or 500 without CORS headers shows up in the browser as a confusing CORS error.
  6. Allowing null as an origin, which sandboxed iframes and local files send.

For a public, credential-free API such as open data, Access-Control-Allow-Origin: * is fine.

Other security headers for APIs

JSON APIs are not rendered as pages, but a few headers still help, especially if error pages or files are ever served from the same host.

Header Value Purpose
Strict-Transport-Security max-age=63072000; includeSubDomains Browsers use HTTPS only from now on
X-Content-Type-Options nosniff Stops browsers guessing a different content type
Cache-Control no-store on sensitive responses Keeps tokens and personal data out of caches
Content-Security-Policy default-src 'none'; frame-ancestors 'none' A JSON API needs no scripts, frames or images
Referrer-Policy no-referrer Do not leak URLs
Content-Type application/json; charset=utf-8 Always set it correctly

Also remove headers that reveal internals (X-Powered-By, detailed Server strings), and always serve the API over HTTPS only, redirecting or refusing plain HTTP.

Node.js A security headers helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If your API sets cookies (sessions, refresh tokens), set these flags:

HTTP
Set-Cookie: refresh=abc123; Path=/auth; HttpOnly; Secure; SameSite=Strict; Max-Age=2592000
Flag Effect
HttpOnly JavaScript cannot read the cookie, which limits damage from XSS
Secure Sent only over HTTPS
SameSite=Strict or Lax Not sent on most cross-site requests, which blocks most CSRF; None requires Secure and allows cross-site use
Path Limits which URLs receive it (a refresh cookie needs only /auth)
Max-Age Lifetime; omit for a session cookie

Cookie-authenticated APIs need CSRF protection (SameSite plus a CSRF token or custom header check). APIs that read a bearer token from the Authorization header are not affected by CSRF, because browsers do not attach that header automatically.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these URLs has a different origin from https://app.example.com?

    The host differs (api versus app). Paths, query strings and fragments do not change the origin.
  2. 2. Who enforces CORS?

    The server only sends headers. The browser decides whether JavaScript may read the response.
  3. 3. Which request triggers a preflight?

    Non-simple methods or headers make the browser send an OPTIONS request first to check permission.
  4. 4. Why is reflecting the Origin header with Allow-Credentials true dangerous?

    Echoing any origin grants every site access, including with cookies. Use an allowlist.
  5. 5. Which cookie flag stops JavaScript from reading a cookie?

    HttpOnly hides the cookie from document.cookie, so an XSS bug cannot steal it directly.

Summary

  • An origin is scheme + host + port; browsers block cross-origin reads unless the server sends CORS headers.
  • Non-simple requests trigger an OPTIONS preflight; answer with allowed methods, headers and Max-Age.
  • Use an exact-origin allowlist, add Vary: Origin, never combine * with credentials, and remember CORS is not authentication.
  • Send HSTS, nosniff, a restrictive CSP and no-store on sensitive responses, and always serve HTTPS.
  • Cookies need HttpOnly, Secure and SameSite; cookie-based APIs also need CSRF protection.

Next: Pagination: Offset, Page and Cursor