CORS (Cross-Origin Resource Sharing) is the mechanism letting JavaScript from one origin (domain:port:scheme) request resources from another. Without CORS, browsers block fetch/XHR. Setup: HTTP headers Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers. For credentials and non-simple requests — preflight (OPTIONS).
Below: step-by-step, working examples, common pitfalls, FAQ.
* only for public APIs without credentialsAccess-Control-Allow-Methods: GET, POST, PUTAccess-Control-Allow-Credentials: true + NOT wildcardAccess-Control-Max-Age: 86400 (24h)| Scenario | Config |
|---|---|
| nginx simple CORS | add_header 'Access-Control-Allow-Origin' 'https://app.example.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type' always; |
| nginx preflight | if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Max-Age' 86400;
return 204;
} |
| Apache .htaccess | Header set Access-Control-Allow-Origin "https://app.example.com"
Header set Access-Control-Allow-Credentials "true" |
| Express.js | app.use(cors({ origin: 'https://app.example.com', credentials: true })); |
| Whitelist multiple origins | map $http_origin $cors_origin {
default "";
"~^https?://(app|api)\.example\.com$" $http_origin;
}
add_header 'Access-Control-Allow-Origin' $cors_origin always; |
* + Credentials=true — browsers block silentlySimple request: GET/HEAD/POST + only standard headers (Accept, Content-Type in form/text). No preflight OPTIONS; goes through directly. Non-simple = preflight required.
Security spec: credentials (cookies) + wildcard = theoretically any site could steal sessions. Browsers block the combo.
DevTools → Network → red request → Headers. Console shows "CORS policy: ..." with the cause. <a href="/en/cors">Enterno CORS checker</a> simulates different Origin headers.
<a href="/en/cors">Enterno CORS checker</a> — enter URL + Origin → see returned headers.