CORS, CSP and Security Headers

Configure cross-origin access and browser security headers correctly instead of copying permissive snippets.

Intermediate · about 3 hours · difficulty 3/5

Learn first: HTTP in Depth, Sessions and Cookies

Browsers enforce the same-origin policy: a page from https://app.example.com cannot freely read responses from https://api.other.com. Backends relax or reinforce this with headers.

CORS (Cross-Origin Resource Sharing)

CORS lets your API tell browsers which other origins may call it.

  • Simple requests get an Access-Control-Allow-Origin check on the response.
  • Non-simple requests (custom headers, JSON bodies with PUT/DELETE) trigger a preflight OPTIONS request first.
  • To send cookies cross-origin you need Access-Control-Allow-Credentials: true and an explicit origin, never *.
  • Keep an allowlist of origins. CORS is a browser protection, not an authentication mechanism: curl ignores it entirely.

CSP (Content Security Policy)

The Content-Security-Policy header tells the browser which sources of scripts, styles, images and frames are allowed. A strict CSP (for example nonce-based scripts) greatly reduces the impact of XSS. Relevant whenever your backend serves HTML.

Other headers worth setting

  • Strict-Transport-Security (HSTS)
  • X-Content-Type-Options: nosniff
  • Referrer-Policy
  • frame-ancestors in CSP (or X-Frame-Options) against clickjacking

Middleware such as helmet (Node) sets sensible defaults.

Pitfalls

  • Reflecting any Origin header back with credentials allowed. That is effectively disabling the protection.

You are ready to move on when you can explain a preflight request from the network tab and your API allows exactly the origins it should.

Key concepts

  • Same-origin policy
  • CORS and preflight requests
  • Credentials and CORS
  • Content Security Policy
  • Clickjacking protection
  • helmet and header middleware

Mini project

Serve a frontend from one origin and your API from another, get cookie-based auth working across them with a strict CORS allowlist, then add a CSP and verify a test inline script is blocked.

Check yourself

Why does CORS not protect your API from a malicious script running on a server?

Free resources