|
| 1 | +--- |
| 2 | +created: 2026-03-19 |
| 3 | +title: CORS Preflight (OPTIONS) |
| 4 | +tags: |
| 5 | + - seed |
| 6 | +--- |
| 7 | +**CORS Preflight** is a security "handshake" used by web browsers to verify that a cross-origin request is safe to send. It ensures that the server understands and permits the specific HTTP method and headers intended by the client. |
| 8 | + |
| 9 | +### The Mechanism |
| 10 | + |
| 11 | +- **HTTP Method:** Uses the `OPTIONS` method. |
| 12 | + |
| 13 | +- **Timing:** Occurs automatically before the **Actual Request** (e.g., POST, PUT, DELETE). |
| 14 | + |
| 15 | +- **The Handshake:** 1. The browser sends an `OPTIONS` request with `Access-Control-Request-Method`. |
| 16 | + |
| 17 | + 2. The server responds with `Access-Control-Allow-Methods` and `Access-Control-Allow-Origin`. |
| 18 | + |
| 19 | + 3. If the response matches the intent, the browser sends the actual data. |
| 20 | + |
| 21 | +### Trigger Conditions (Non-Simple Requests) |
| 22 | + |
| 23 | +A Preflight is triggered if the request meets any of these "Non-Simple" criteria: |
| 24 | + |
| 25 | +- **HTTP Methods:** `PUT`, `DELETE`, `PATCH`, `CONNECT`, `OPTIONS`, `TRACE`. |
| 26 | + |
| 27 | +- **Content-Type:** Any type other than `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain` (most notably **`application/json`**). |
| 28 | + |
| 29 | +- **Custom Headers:** Any request containing headers like `Authorization`, `X-Custom-Header`, etc. |
| 30 | + |
| 31 | +### Key Headers |
| 32 | + |
| 33 | +- **Origin:** The domain initiating the request (e.g., `https://my-app.com`). |
| 34 | + |
| 35 | +- **Access-Control-Allow-Origin:** Specifies which domains are permitted to access the resource. |
| 36 | + |
| 37 | +- **Access-Control-Allow-Methods:** A comma-separated list of allowed HTTP methods. |
| 38 | + |
| 39 | +- **Access-Control-Max-Age:** Defines how long (in seconds) the results of a preflight request can be cached to avoid redundant `OPTIONS` calls. |
| 40 | + |
| 41 | +### Why it Matters |
| 42 | + |
| 43 | +- **Security:** Prevents malicious websites from forcing a user's browser to send unintended requests to a different server. |
| 44 | + |
| 45 | +- **Legacy Compatibility:** Protects older servers that were not designed to handle modern cross-origin requests or specific HTTP methods. |
| 46 | + |
0 commit comments