Understanding Preflight OPTIONS Requests: The CORS Gatekeeper

Browsers enforce the same-origin policy to prevent malicious cross-site requests. Preflight acts as a “handshake” before sensitive requests, asking: “Server, are you cool with this?” 🔥 Triggers for Preflight: Non-simple HTTP methods (PUT, DELETE, PATCH) Custom headers (e.g., X-API-Token) “Advanced” Content-Types (e.g., application/json) Credentialed requests (with cookies/auth) ✅ Simple requests (GET/POST with basic headers) skip preflight! 🔁 How Preflight Works: A 2-Step Dance sequenceDiagram Browser->>Server: OPTIONS Request (Preflight) Note left of Browser: Headers sent:<br>📍 Origin<br>📍 Access-Control-Request-Method<br>📍 Access-Control-Request-Headers alt Server Allows Server-->>Browser: 200 OK + CORS Headers Note right of Server: Headers returned:<br>✅ Access-Control-Allow-Origin<br>✅ Access-Control-Allow-Methods<br>✅ Access-Control-Allow-Headers Browser->>Server: Actual Request (e.g., DELETE) else Server Denies Server-->>Browser: CORS Error Blocked! end ⚙️ Server-Side Setup Essentials Handle OPTIONS requests correctly: ...

October 21, 2025 · 2 min · 309 words · 0xuki