| 1 | --- |
| 2 | title: "htmx.config.mode" |
| 3 | description: "Set request mode for fetch API" |
| 4 | --- |
| 5 | |
| 6 | The `htmx.config.mode` option sets the `mode` option for fetch requests. |
| 7 | |
| 8 | This is the **only** way to set the fetch mode — the `mode` key in per-element `hx-config` |
| 9 | attributes is ignored and always reset to this global value. This prevents injected markup |
| 10 | from widening request scope (e.g. switching from `same-origin` to `cors`). |
| 11 | |
| 12 | **Default:** `"same-origin"` |
| 13 | |
| 14 | ## Valid Values |
| 15 | |
| 16 | - `"same-origin"` - Only allow same-origin requests (default, most secure) |
| 17 | - `"cors"` - Allow cross-origin requests |
| 18 | - `"no-cors"` - Limited cross-origin requests |
| 19 | - `"navigate"` - Navigation mode |
| 20 | |
| 21 | ## Example |
| 22 | |
| 23 | ```javascript |
| 24 | htmx.config.mode = "cors"; |
| 25 | ``` |
| 26 | |
| 27 | ```html |
| 28 | <meta name="htmx-config" content='{"mode":"cors"}'> |
| 29 | ``` |
| 30 | |
| 31 | ## Security |
| 32 | |
| 33 | The default `"same-origin"` means the browser will reject any cross-origin fetch outright, |
| 34 | even if an attacker injects an `hx-get` pointing to an external URL. |
| 35 | |
| 36 | If your app legitimately needs CORS (e.g. an API on a different subdomain), set `mode` globally |
| 37 | and pair it with a `Content-Security-Policy` `connect-src` directive to limit reachable origins: |
| 38 | |
| 39 | ```html |
| 40 | <meta http-equiv="Content-Security-Policy" |
| 41 | content="connect-src 'self' https://api.example.com"> |
| 42 | ``` |
| 43 | |
| 44 | This way, even if an attacker injects a target URL, CSP blocks connections to origins you |
| 45 | haven't explicitly allowed. |