Debian Codegraph @

www/src/content/reference/01-attributes/17-hx-headers.md

raw symbols SCIP
1 ---
2 title: "hx-headers"
3 description: "Adds custom headers to the request"
4 ---
5
6 The `hx-headers` attribute allows you to add to the headers that will be submitted with an AJAX request.
7
8 By default, the value of this attribute is a list of name-expression values
9 in [JSON (JavaScript Object Notation)](https://www.json.org/json-en.html)
10 format.
11
12 ## Syntax
13
14 ```html
15 <div hx-get="/data" hx-headers='{"myHeader": "My Value"}'>Get Data</div>
16 ```
17
18 If you wish for `hx-headers` to *evaluate* the values given, you can prefix the values with `javascript:` or `js:`.
19
20 ```html
21 <div hx-get="/example" hx-headers='{"myHeader": "My Value"}'>Get Some HTML, Including A Custom Header in the Request</div>
22
23 <div hx-get="/example" hx-headers='js:{myVal: calculateValue()}'>Get Some HTML, Including a Dynamic Custom Header from Javascript in the Request</div>
24 ```
25
26 ## Inheritance
27
28 By default, `hx-headers` does not inherit to child elements. Use the `:inherited` modifier to apply headers to all htmx requests within a subtree. This is useful for propagating a CSRF token across a section of the page:
29
30 ```html
31 <div hx-headers:inherited='js:{"X-CSRF-Token": getCsrfToken()}'>
32 <button hx-post="/transfer">Submit</button>
33 <button hx-delete="/item/1">Delete</button>
34 </div>
35 ```
36
37 A child declaration of a header overrides a parent declaration.
38
39 ## Security Considerations
40
41 * By default, the value of `hx-headers` must be valid [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON).
42 It is **not** dynamically computed. If you use the `javascript:` prefix, be aware that you are introducing
43 security considerations, especially when dealing with user input such as query strings or user-generated content,
44 which could introduce a [Cross-Site Scripting (XSS)](https://owasp.org/www-community/attacks/xss/) vulnerability.
45
46 * Whilst far from being a foolproof solution
47 to [Cross-Site Request Forgery](https://owasp.org/www-community/attacks/csrf), the `hx-headers` attribute can support
48 backend services to
49 provide [CSRF prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html).
50 For more information see the [CSRF Prevention](https://htmx.org/docs/#csrf-prevention) section.
51
52