Understanding CORS and Content Security Policy (CSP)
A frequent point of confusion and a common interview topic is:
What is CORS, and why does the browser make a preflight OPTIONS request? How does a Content Security Policy (CSP) defend web applications?
To answer this, you must explain the Same-Origin Policy (SOP), the cross-origin preflight handshake, and how CSP restricts document execution.
1. Same-Origin Policy (SOP) & CORS
The Same-Origin Policy is a fundamental browser security mechanism. It prevents scripts on one origin (e.g., attacker.com) from reading or writing data from another origin (e.g., bank.com).
However, sites often need to load resources from other API endpoints. CORS (Cross-Origin Resource Sharing) is a mechanism that allows servers to explicitly declare who is allowed to fetch their resources.
2. CORS Preflight Handshake (OPTIONS)
When a web application makes a cross-origin request using fetch or Axios, the browser inspects the request. If it is classified as a non-simple request, the browser automatically sends a preflight request using the OPTIONS method before sending the actual request.
What Makes a Request Non-Simple?
- HTTP methods other than
GET,HEAD, orPOST. - Custom headers (e.g.,
Authorization,Content-Typeother thanapplication/x-www-form-y-urlencoded,multipart/form-data, ortext/plain).
Preflight Flow:
Client Browser API Server (Cross-Origin)
│ │
│ ─── 1. OPTIONS (Preflight check) ───> │
│ <── 2. Allow headers, origin, methods ── │ (Verifies client is allowed)
│ │
│ ─── 3. Actual Request (e.g. POST) ──> │
│ <── 4. Response with data ─────────── │If the server does not respond to the OPTIONS request with appropriate headers (like Access-Control-Allow-Origin), the browser blocks the actual request.
3. Content Security Policy (CSP)
A Content Security Policy (CSP) is an HTTP response header that tells the browser which dynamic resources are allowed to load and execute. It is the primary defense against XSS.
Common CSP Directives:
default-src 'self': Only allow loading resources from the site's own origin.script-src 'self' https://apis.google.com: Allow scripts only from the current origin and Google APIs.img-src * data:: Allow images from any source (*) and base64 inline images (data:).
Example CSP Header:
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-random123'; object-src 'none';Setting script-src to use a nonce (a random, single-use token generated per request) ensures that only <script> tags with the matching nonce attribute execute, blocking any inline scripts injected by an attacker.
Key Takeaways
- Same-Origin Policy blocks reading cross-origin data by default.
- CORS allows servers to relax this restriction using headers.
- Preflight requests (
OPTIONS) are sent for non-simple requests to ensure the server understands the cross-origin protocol before the actual request is made. - CSP is a powerful header-driven browser security layer that mitigates XSS by dictating source access rules.