Debian Codegraph @

www/src/content/reference/03-events/01-htmx-config-request.md

raw symbols SCIP
1 ---
2 title: "htmx:config:request"
3 description: "Configure request before it's sent"
4 ---
5
6 The `htmx:config:request` event fires after request parameters are built but before validation and sending.
7
8 ## When It Fires
9
10 After htmx has constructed the request context but before [`htmx:confirm`](/reference/events/htmx-confirm) or [`htmx:before:request`](/reference/events/htmx-before-request).
11
12 ## Event Detail
13
14 The event provides a `ctx` object with the following structure:
15
16 ```javascript
17 {
18 sourceElement, // Element that triggered the request
19 sourceEvent, // Event that triggered it
20 target, // Where the response will go
21 select, // hx-select value
22 selectOOB, // hx-select-oob value
23 swap, // hx-swap value
24 push, // hx-push-url value
25 replace, // hx-replace-url value
26 transition, // Whether to use view transitions
27 request: {
28 validate, // Whether to validate the form
29 action, // Request URL
30 method, // HTTP method
31 headers, // Request headers object
32 body, // Request body (FormData)
33 credentials, // Fetch credentials mode
34 mode, // Fetch mode
35 cache, // Fetch cache mode
36 timeout, // Timeout in milliseconds
37 // ... any other fetch options
38 }
39 }
40 ```
41
42 You can modify any property to change the request.
43
44 Call `evt.preventDefault()` to cancel the request.
45
46 ## Examples
47
48 ### Add authentication to all requests
49
50 ```javascript
51 document.body.addEventListener('htmx:config:request', function(evt) {
52 evt.detail.ctx.request.headers['X-Auth-Token'] = getAuthToken();
53 });
54 ```
55
56 ### Set longer timeout for specific endpoint
57
58 ```javascript
59 htmx.on('htmx:config:request', (evt) => {
60 if (evt.detail.ctx.request.action.includes('/slow-endpoint')) {
61 evt.detail.ctx.request.timeout = 30000;
62 }
63 });
64 ```
65
66 ### Include credentials for CORS requests
67
68 ```javascript
69 document.body.addEventListener('htmx:config:request', function(evt) {
70 if (evt.detail.ctx.request.action.startsWith('https://api.example.com')) {
71 evt.detail.ctx.request.credentials = 'include';
72 evt.detail.ctx.request.mode = 'cors';
73 }
74 });
75 ```
76
77 ### Cancel request based on condition
78
79 ```javascript
80 htmx.on('htmx:config:request', (evt) => {
81 if (!isUserAuthorized()) {
82 evt.preventDefault();
83 }
84 });
85 ```
86
87 ## Notes
88
89 - This is the ideal place to modify request configuration globally
90 - Changes made here apply after [`hx-config`](/reference/attributes/hx-config) attributes are processed
91 - Use this for cross-cutting concerns like authentication, logging, or global timeouts