What is a CORS preflight request, and when does the browser send one automatically?
Short answer
For 'non-simple' requests (using methods other than GET/HEAD/POST, custom headers, or a Content-Type other than a few basic ones), the browser automatically sends an OPTIONS preflight request before the actual request, asking the server 'are you willing to accept this…
Advertisement
AModel answer
For 'non-simple' requests (using methods other than GET/HEAD/POST, custom headers, or a Content-Type other than a few basic ones), the browser automatically sends an OPTIONS preflight request before the actual request, asking the server 'are you willing to accept this cross-origin request?' via Access-Control-Request-Method and Access-Control-Request-Headers headers -- the server must respond with matching Access-Control-Allow-* headers, and only if the preflight succeeds does the browser send the actual request.
Example
// Browser automatically sends this BEFORE a PUT request with a custom header: // OPTIONS /api/products/5 HTTP/1.1 // Access-Control-Request-Method: PUT // Access-Control-Request-Headers: X-Custom-Header // Server must respond with: // Access-Control-Allow-Methods: PUT // Access-Control-Allow-Headers: X-Custom-Header
Real-world example
A team debugging why their PUT requests with a custom Authorization-like header mysteriously fail cross-origin discovers the API never explicitly allows that custom header in its CORS policy, causing the preflight OPTIONS request to fail silently before the real request is ever sent.
Likely follow-ups
- What HTTP methods/headers count as 'simple' and avoid triggering preflight?
- How can you cache preflight results to avoid repeating them on every request?
Related topics