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:

  1. Non-simple HTTP methods (PUT, DELETE, PATCH)
  2. Custom headers (e.g., X-API-Token)
  3. “Advanced” Content-Types (e.g., application/json)
  4. 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 verbs
  • Access-Control-Allow-Headers: Approved custom headers
  • Access-Control-Max-Age: Preflight cache duration (reduces overhead!)

🚫 Common Preflight Pitfalls & Fixes

  1. Missing OPTIONS handler → Returns 405 Method Not Allowed
    Fix: Implement OPTIONS route in your backend.

  2. Undefined headersCORS error: Request header not allowed
    Fix: Add all custom headers to Access-Control-Allow-Headers.

  3. Certificate mismatches → Preflight fails on HTTPS sites with HTTP APIs
    Fix: Ensure consistent protocols.


⚡ Pro Tips for Developers

  1. Debugging: Check “Network” tab → filter OPTIONS requests.
  2. Caching: Set Access-Control-Max-Age to reduce preflight traffic.
  3. Security: Never use Access-Control-Allow-Origin: * with credentials!
  4. Testing: Use curl -X OPTIONS http://your-api.com to 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!)