---
title: "hx-csp"
description: "Make htmx work under strict Content Security Policy"
category: "Security"
icon: "icon-[mdi--shield-lock-outline]"
keywords: ["nonce", "csp", "security", "trusted types", "xss", "content security policy"]
---
The `hx-csp` extension provides Content Security Policy enforcement for htmx across three layers: nonce gating to prevent HTML injection, Trusted Types integration to restrict DOM writes, and safe eval to eliminate `unsafe-eval` from your CSP.
## Installing
```html
```
## The hx-nonce Attribute
The `hx-nonce` attribute is how the server signals to the extension that an htmx element was intentionally rendered by trusted server-side code. When htmx initialises an element, the extension checks that its `hx-nonce` matches the page nonce — if it doesn't match or is missing, all htmx attributes are stripped and the element is inert.
Your templating engine should stamp `hx-nonce` on every element that carries htmx attributes:
```html
```
**Important:** `hx-nonce` alone does not guarantee XSS protection. It proves the element was rendered by the server, but it says nothing about the safety of the attribute values on that element. Any htmx attribute that includes user-supplied data must still be properly escaped by your templating engine:
```html
...
...
```
All major templating engines escape HTML entities (`"`, `'`, `<`, `>`, `&`) by default — make sure you are not bypassing this with raw/unescaped output filters (`| raw`, `| safe`, `raw()` etc.), which would allow a `"` in user input to break out of the attribute and inject new attributes.
URL-valued attributes (`hx-get`, `hx-post`, etc.) are also blocked by the extension if the value is a `js:` or `javascript:` URI — these schemes survive entity encoding and are not valid action URLs.
**Never put user-controlled data in JS-evaluated attributes.** `hx-on:*`, `hx-vals js:`, `hx-confirm js:`, and trigger filters are evaluated as JavaScript. HTML escaping does not protect you here — the browser decodes HTML entities *before* passing the string to the JS engine, so an attacker can break out of a string literal even if your template engine has escaped the value.
There is no standard JavaScript string escaping filter in most templating language. Even frameworks that provide one (Django's `escapejs`, Rails' `escape_javascript`) require you to apply it correctly every time, and they may not protect against every injection vector in a JS context.
The only safe pattern is to keep user data out of the attribute entirely and pass it via `data-*`:
```html