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:
// Express.js example
app.options('/data', (req, res) => {
res.header('Access-Control-Allow-Origin', 'https://your-client.com')
.header('Access-Control-Allow-Methods', 'GET,PUT,DELETE')
.header('Access-Control-Allow-Headers', 'X-API-Key, Content-Type')
.header('Access-Control-Max-Age', '86400') // Cache for 24h
.sendStatus(200);
});
Key Headers:
Access-Control-Allow-Origin: Permitted domains (use*cautiously!)Access-Control-Allow-Methods: Allowed HTTP verbsAccess-Control-Allow-Headers: Approved custom headersAccess-Control-Max-Age: Preflight cache duration (reduces overhead!)
🚫 Common Preflight Pitfalls & Fixes
Missing OPTIONS handler → Returns
405 Method Not Allowed
Fix: Implement OPTIONS route in your backend.Undefined headers →
CORS error: Request header not allowed
Fix: Add all custom headers toAccess-Control-Allow-Headers.Certificate mismatches → Preflight fails on HTTPS sites with HTTP APIs
Fix: Ensure consistent protocols.
⚡ Pro Tips for Developers
- Debugging: Check “Network” tab → filter
OPTIONSrequests. - Caching: Set
Access-Control-Max-Ageto reduce preflight traffic. - Security: Never use
Access-Control-Allow-Origin: *with credentials! - Testing: Use
curl -X OPTIONS http://your-api.comto inspect headers.
🔑 Why This Matters
Preflight isn’t bureaucracy—it’s critical web security infrastructure. By validating cross-origin requests upfront:
- Servers control their resources 🛡️
- Browsers prevent malicious data access 🚫
- Web APIs remain flexible yet secure 🔒
Next time you see an OPTIONS request, salute your silent guardian! 🫡
(Want a deep dive into CORS headers? Let me know in the comments!)
