Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 28 ยท HTMX and Alpine Together

Server-Side Setup: Fragments, Partials and Security

Return HTML fragments from Laravel, Django, Express or Flask, detect HX-Request, send CSRF tokens, escape output, and lock down HTMX and Alpine.js.

Everything so far ran against a mock server. In a real project, your backend answers HTMX requests, and that changes what you must think about. The server decides what HTML to return, which requests are allowed and how user input is displayed. Getting these three things right is what makes an HTMX site secure and pleasant to maintain.

HTMX does not care which language you use. Any framework that can return a string of HTML works. This lesson shows the pattern in four popular frameworks as read-only snippets (the sandbox cannot run them), and then demonstrates the security rules with runnable stand-ins. You should already know Your First HTMX Request and Forms, Validation and Submissions.

Fragments and partials

A fragment (also called a partial) is a piece of HTML without <html>, <head> or the site layout. HTMX swaps it into the page. A good setup has one template per fragment, and the full page template includes the same fragment. That way the first page load and every later HTMX update use the same markup, and you never write the view twice.

flowchart LR
    A["Full page request"] --> B["Layout + header + fragment"]
    C["HTMX request<br/>HX-Request: true"] --> D["Fragment only"]
    B --> E["Browser shows the page"]
    D --> F["HTMX swaps it in"]

The same fragment template serves both kinds of request.

Detecting an HTMX request

HTMX adds the header HX-Request: true to every request it sends. Your server can return the fragment alone when the header is present and the whole page otherwise. This is what makes links and forms work without JavaScript, and it is called progressive enhancement. Other useful request headers are HX-Target (the id of the target element), HX-Trigger (the id of the element that fired) and HX-Boosted (the request came from hx-boost).

One route, two answers

The server code is one handler. HTMX gets the list, and a normal navigation (the second button simulates it) gets the full document around the same list.

If a CDN or browser cache sits in front of such a route, add Vary: HX-Request to the response. Otherwise a cache can hand the fragment to a person who typed the URL into the address bar.

The same idea in four frameworks

These snippets are read-only. Each returns a fragment for HTMX and the full page otherwise.

Laravel (Blade has @fragment, so one template can hold both):

PHP
Route::get('/team', function (Request $request) {
    $members = Member::orderBy('name')->get();

    $view = view('team', ['members' => $members]);

    return $request->header('HX-Request')
        ? $view->fragment('member-list')
        : $view;
});
BLADE
{{-- resources/views/team.blade.php --}}
@extends('layouts.app')
@section('content')
    @fragment('member-list')
        <ul id="members">
            @foreach ($members as $member)
                <li>{{ $member->name }}</li>
            @endforeach
        </ul>
    @endfragment
@endsection

Django (a partial template included by the page template):

Python
def team(request):
    members = Member.objects.order_by("name")
    template = "team/_list.html" if request.headers.get("HX-Request") else "team/page.html"
    response = render(request, template, {"members": members})
    response["Vary"] = "HX-Request"
    return response

Express (with any template engine; here EJS):

JavaScript
app.get("/team", async (req, res) => {
  const members = await db.members.findAll({ order: ["name"] });
  const view = req.get("HX-Request") ? "team/_list" : "team/page";
  res.vary("HX-Request").render(view, { members });
});

Flask (Jinja):

Python
@app.get("/team")
def team():
    members = Member.query.order_by(Member.name).all()
    template = "team/_list.html" if request.headers.get("HX-Request") else "team/page.html"
    return render_template(template, members=members)

In every framework, the page template simply includes the list partial, so there is one source of truth.

Authorization: every fragment is an endpoint

A fragment URL is a normal URL. Anyone can open it in a browser or send it with curl, with or without the HX-Request header. So every fragment route needs the same checks as any other route: is the user signed in, are they allowed to see this record, may they change it? Hiding a button in the page is not protection.

When a check fails, return a real status (401, 403, 404), not 200 with an apology. By default HTMX only swaps 2xx responses, so an error status leaves the page alone and fires htmx:responseError, which you can use to show a message (see Events, Headers and JavaScript Integration).

CSRF tokens with hx-headers

Any request that changes data (POST, PUT, PATCH, DELETE) needs CSRF protection if your app uses cookie sessions. The simplest way to give every HTMX request the token is hx-headers on the <body> tag. Attributes like this are inherited by every element inside.

CSRF header, 403 and a failed request

The first button succeeds because the header on the wrapping element was inherited (in a real page you put it on <body>). The second button overrides the header with an empty value, so the server answers 419 and HTMX leaves the target alone. Our listener then explains what happened. The admin button fails with 403 until you "sign in", which in a real app would be the server's own session check.

Framework-specific forms of the header (read-only):

HTML
<!-- Laravel -->
<body hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'>

<!-- Django -->
<body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>

Escaping output and XSS

HTMX inserts whatever HTML you send. If that HTML contains unescaped user input, an attacker can inject markup and scripts. This is cross-site scripting (XSS), and the defense is the same as for any server-rendered page: escape every untrusted value when you build HTML.

Modern template engines (Blade {{ }}, Django, Jinja, EJS <%= %>) escape by default. The danger is the escape hatch: {!! !!}, |safe, <%- %>, or building HTML with string concatenation as the mock servers in this track do. The demo below shows both sides.

Unescaped versus escaped user input

The "unsafe" server pasted the name into HTML, so the browser built a real <img> element, and its onerror handler would run any script an attacker chose. The escaped version produced zero elements: the same characters are shown as text. The demo's payload only sets a harmless variable, but a real one could steal data or act as the user.

Rules that prevent almost every case:

  • Escape on output, in the template, using the framework's default escaping.
  • Never mark user input as "safe".
  • Do not put user input inside <script> blocks, event-handler attributes or inline styles.
  • For URLs, accept only the schemes you expect (https:, mailto:), because javascript: links also run code.
  • When you must show user-written HTML (comments with formatting), sanitize it with a maintained library on the server.

Alpine expressions deserve the same care. An attribute such as x-data="{ name: 'O'Brien' }" breaks on the quote, and a crafted value can run code, so pass values through JSON encoding (@js($name) in Blade, |json_script in Django) or data- attributes.

Keeping user content inert with hx-disable

If a page displays user-written HTML at all, an attacker's markup may include hx- attributes, such as a button that sends a request on your behalf. The attribute hx-disable tells HTMX to ignore an element and everything inside it.

hx-disable makes user content inert

The trusted button sends a request and updates the counter. The identical-looking button inside hx-disable does nothing at all: HTMX never processed it.

Content-Security-Policy and Alpine's CSP build

A Content-Security-Policy (CSP) header tells the browser which scripts it may run. A strict policy blocks injected inline scripts, which is excellent XSS insurance. Two details matter for this stack.

HTMX itself works with a strict policy as long as you serve its file from your own domain (or an allowed one) and do not enable eval-based features. Alpine's standard build evaluates expressions with new Function, which a strict policy forbids (unsafe-eval). Alpine ships a second build for this case, the CSP build, which uses its own small expression parser. It supports property access, method calls and simple operators, but not arbitrary JavaScript, and you move complex logic into Alpine.data components:

HTML
<script defer src="https://cdn.jsdelivr.net/npm/@alpinejs/[email protected]/dist/cdn.min.js"></script>
<script>
  document.addEventListener("alpine:init", () => {
    Alpine.data("dropdown", () => ({
      open: false,
      toggle() { this.open = !this.open; },
    }));
  });
</script>

<div x-data="dropdown">
  <button @click="toggle">Menu</button>
  <ul x-show="open">...</ul>
</div>

A matching response header could look like this. Inline <script> blocks need a nonce, so the better habit is to move such code into a file:

TEXT
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'

HTMX also adds a small style rule for its indicators; set htmx.config.includeIndicatorStyles = false (or its meta tag) and write the rules yourself if your policy forbids inline styles.

HTMX configuration for safety

HTMX is configured through htmx.config or a <meta name="htmx-config"> tag in the <head>. These settings matter most for security (read-only example):

HTML
<meta name="htmx-config" content='{
  "allowEval": false,
  "allowScriptTags": false,
  "selfRequestsOnly": true
}'>
Setting Effect
allowEval When false, HTMX never uses eval. Features that need it stop working: js: prefixes in hx-vals, hx-on: attributes and trigger filters.
allowScriptTags When false, <script> tags inside swapped fragments are not executed.
selfRequestsOnly When true (the default in HTMX 2), requests may only go to your own origin.
includeIndicatorStyles Whether HTMX injects its small indicator CSS.

The allowEval switch and the Alpine CSP build solve the same problem from two sides. If you want a strict policy, turn both on and write your logic in files and Alpine.data components.

A server-side checklist

Before you ship an HTMX and Alpine page, check these items:

  1. Fragment routes enforce authentication and authorization.
  2. Write requests carry a CSRF token (hx-headers on <body>).
  3. Every untrusted value is escaped when HTML is built.
  4. User-written HTML is sanitized and wrapped in hx-disable.
  5. Responses that differ by HX-Request send Vary: HX-Request.
  6. Errors return real status codes, and the page handles htmx:responseError.
  7. A CSP is in place, with the Alpine CSP build if you forbid unsafe-eval.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How can a server tell that a request came from HTMX?

    HTMX adds HX-Request: true to every request, so the server can return a fragment instead of a full page.
  2. 2. Why must fragment endpoints do their own authorization checks?

    A fragment route is an ordinary URL. Hiding the button in the page does not stop someone from requesting it, so the server must check every time.
  3. 3. A server builds HTML with "Hello, " + name + "!" and returns it to HTMX. What is the risk?

    Unescaped user input becomes real HTML in the page. Escape every untrusted value when you output it.
  4. 4. Which setup lets Alpine run under a Content-Security-Policy that forbids unsafe-eval?

    The CSP build parses expressions without new Function, and complex logic lives in registered Alpine.data components.
  5. 5. What does hx-disable do?

    HTMX does not process hx- attributes inside an hx-disable element, which keeps user-supplied markup inert.

Summary

  • A fragment is HTML without the layout. Use one partial template for both the first page load and HTMX updates.
  • HTMX sends HX-Request: true; return a fragment for it and a full page otherwise, with Vary: HX-Request if anything caches the response.
  • Authorize every fragment endpoint on the server and return real error statuses; HTMX does not swap 4xx or 5xx responses by default.
  • Send CSRF tokens with hx-headers on <body>.
  • Escape all untrusted output; use hx-disable around user-written HTML.
  • For strict CSPs, use Alpine's CSP build and allowEval: false, and keep selfRequestsOnly on.

Continue with Project: Todo List with HTMX and Alpine.