CORS & Web Security Headers
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that governs whether client-side JavaScript from one origin is permitted to access resources from a different origin.
Think of it like this: Like passport control at an international border: when your JavaScript tries to access another domain’s private data, the browser asks the destination server: "Do you explicitly authorize visitors from this origin?"
Step 1 of 4
Syntax
Origin: https://app.example.com
Access-Control-Allow-Origin: https://app.example.comWorked example
Request
OPTIONS /api/data HTTP/1.1
Origin: https://app.client.com
Access-Control-Request-Method: DELETEResponse
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.client.com
Access-Control-Allow-Methods: GET, POST, DELETE
Access-Control-Max-Age: 86400The browser pre-clears authorization before executing the destructive DELETE method. The server grants permission and caches the verdict for 24 hours.
Same-Origin Policy (SOP) vs CORS
The browser Same-Origin Policy forbids scripts from reading responses from a differing scheme, host, or port. CORS provides the HTTP headers that allow servers to declare safe exceptions.
Preflight OPTIONS Requests
- Trigger — Non-simple requests (methods like PUT/DELETE or custom headers like Authorization) trigger an automated preflight.
- OPTIONS check — The browser sends OPTIONS with Access-Control-Request-Method and Access-Control-Request-Headers.
- Server Response — The server returns Access-Control-Allow-Origin, Allow-Methods, Allow-Headers, and Max-Age cache duration.
Essential Web Security Headers
- CSP (Content-Security-Policy) — Prevents XSS and data injection attacks by restricting allowed sources for scripts, images, and styles.
- HSTS (Strict-Transport-Security) — Directs browsers to automatically upgrade all future requests to HTTPS for a declared time.
- X-Content-Type-Options: nosniff — Stops browsers from MIME-sniffing responses away from the declared Content-Type.
Study kit
Module 14 of 18
Intermediate · 3 min · 0 of 18 complete
Module status
Not completed yet
Notessaved locally+
Notes stay in this browser. They are not uploaded.
Suggest an editLearning graph
Prerequisites
Discussion
Loading discussion…
Sign in to ask a question.