Under The Hood
frontend htmx HTMX 1.x / 2.x

HTMX Security: CSRF Token Headers and Untrusted HTML Sanitization

Last updated
Prerequisites:
Cross-Site Request Forgery (CSRF)
Cross-Site Scripting (XSS)
  • htmx
  • security
  • csrf
  • xss
  • sanitization
  • cors

Read at your depth

The practical view

To protect against CSRF attacks in HTMX, attach your server's CSRF token to all outgoing requests using `hx-headers`: `<body hx-headers='{"X-CSRF-Token": "..."}'>`. For XSS protection, always sanitize or escape user-generated content on the server (using server template auto-escaping) before returning HTML partials, because HTMX will execute `<script>` tags present in swapped HTML.

The same idea in other frameworks

react equivalent
React escapes JSX strings by default to prevent XSS; manual `dangerouslySetInnerHTML` is guarded.

Legacy vs modern

Vulnerable Plain Request vs Secure CSRF Header Injection

Plain requests without CSRF tokens are vulnerable to cross-site forgery; `htmx:configRequest` injects security tokens automatically.

before → after
Missing CSRF Protection
<button hx-post="/delete-account">Delete</button> // ❌ Vulnerable to CSRF attacks
Automated CSRF Token Injection
document.body.addEventListener('htmx:configRequest', (e) => e.detail.headers['X-CSRF-Token'] = token); // ✅ NEW

Interview gotchas

Context

Interviewers test your knowledge of HTMX script execution behavior and XSS vectors.

The mechanical answer

Yes. By default, **HTMX evaluates `<script>` tags** present in swapped HTML responses. If a backend endpoint reflects unsanitized user input (e.g. `<script>stealCookie()</script>`), HTMX will execute it. To disable script execution across the entire application, set `htmx.config.allowScriptTags = false`.

Trap

Never rely on the browser's default `innerHTML` script-blocking behavior when using HTMX; HTMX explicitly extracts and runs script tags unless disabled.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.