Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 28 ยท Getting Started

Setting Up: CDN, Versions and the In-Page Mock Server

Add HTMX 2 and Alpine.js 3 with pinned CDN script tags, learn defer and load order, and read the tiny mock server every example in this track uses.

Both libraries are single JavaScript files. There is no compiler, no bundler and no project template to generate. To start, you add two script tags to a page. This lesson shows the exact tags, explains why their order and the defer attribute matter, and then opens the hood on the mock server that makes every HTMX example in this track work without a real backend.

The two script tags

Here is the minimum page, using the versions this track is written against:

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>My first page</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/htmx.min.js"></script>
  <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
</head>
<body>
  <!-- your markup with hx-* and x-* attributes -->
</body>
</html>

Three details are worth knowing:

  • Pin the version. [email protected] always returns the same file. If you wrote htmx.org@2 or htmx.org@latest, a future release could change behavior underneath a page that used to work. Upgrade deliberately, on your schedule.
  • HTMX loads normally; Alpine uses defer. HTMX scans the document when it finishes loading and processes hx-* attributes, so it can load early. The Alpine CDN build must be loaded with defer, so it starts after the HTML has been parsed. The Alpine documentation requires this, and without it the first scan can miss your components.
  • Order rarely matters between the two, with one exception you will meet in Reusable Components: code that registers components with Alpine.data(...) must run before Alpine starts. Alpine announces that moment with an alpine:init event.

htmx 2 is the current major version. If you find older tutorials using hx-ws, hx-sse or htmx 1.x defaults, remember that those parts moved into extensions in version 2. Everything in this track targets htmx 2.0.x and Alpine.js 3.x.

Why a mock server is needed

HTMX is only interesting when a server answers. In a normal project, hx-get="/products" goes over the network to your backend, which returns an HTML fragment. The live examples on this site run in a sandboxed <iframe> with no backend behind it, so a request to /products would simply fail.

The solution is a mock server that sits inside the page. HTMX makes its requests with the browser's built-in XMLHttpRequest object. We replace that object with a fake class that, instead of using the network, looks up your URL in a table and calls a function you wrote. The function returns a string of HTML, and HTMX swaps it in, exactly as if it had come from Laravel or Django.

flowchart LR
    A["Element with hx-get"] --> B["htmx"]
    B --> C["Fake XMLHttpRequest"]
    C --> D["Routes table"]
    D --> E["Your handler returns HTML"]
    E --> B

The mock replaces the network, not HTMX. Everything above the fake request object is real htmx.

Reading the stub

This is the stub used by every HTMX example. You do not have to memorize it; you only need to know what it offers.

HTML
<script>
  /* Mock server: fake XMLHttpRequest that answers from the routes table */
  const routes = {};
  const server = (method, path, handler) => { routes[method + " " + path] = handler; };
  window.XMLHttpRequest = class {
    constructor() { this.upload = { addEventListener() {} }; this.headers = {}; this.status = 0; this.responseText = ""; this.listeners = {}; }
    addEventListener(type, fn) { (this.listeners[type] ||= []).push(fn); }
    open(method, url) { this.method = method.toUpperCase(); this.url = new URL(url, "http://mock.test"); }
    setRequestHeader(name, value) { this.headers[name.toLowerCase()] = value; }
    overrideMimeType() {}
    getAllResponseHeaders() { return Object.entries(this.out || {}).map(([k, v]) => k + ": " + v).join("\r\n"); }
    getResponseHeader(name) { return (this.out || {})[name] ?? null; }
    abort() { this.cancelled = true; if (this.onabort) this.onabort(); (this.listeners.abort || []).forEach((fn) => fn()); }
    send(body) {
      const form = Object.fromEntries(new URLSearchParams(typeof body === "string" ? body : body ? new URLSearchParams(body).toString() : ""));
      const query = Object.fromEntries(this.url.searchParams);
      const handler = routes[this.method + " " + this.url.pathname];
      setTimeout(() => {
        if (this.cancelled) return;
        const result = handler ? handler({ query, form, headers: this.headers }) : { status: 404, body: "Not found" };
        const reply = typeof result === "string" ? { body: result } : result;
        this.status = reply.status || 200;
        this.out = { "Content-Type": "text/html", ...(reply.headers || {}) };
        this.responseText = this.response = reply.body;
        this.responseURL = this.url.href;
        this.readyState = 4;
        this.onload && this.onload();
        (this.listeners.load || []).forEach((fn) => fn());
      }, 150);
    }
  };
</script>

What matters:

  1. server(method, path, handler) registers a route. The key is the HTTP method plus the path, for example server("GET", "/hello", ...).
  2. The handler receives one object: { query, form, headers }. query holds URL parameters (?q=tea), form holds the body of a POST, and headers holds the request headers HTMX sent, with lowercase names.
  3. The handler returns either a string of HTML (status 200) or an object { status, body, headers } when you need another status code or response headers.
  4. A path with no registered route answers 404 Not found. By default htmx does not swap error responses, which is a useful thing to see for yourself later.
  5. Every reply takes 150 ms, so you can see loading states.

The stub must run before HTMX makes its first request, so it goes above the HTMX script tag. Register your routes anywhere on the page, as long as it happens before the user clicks.

The stub at work

The next example registers two routes and displays what each handler received. Press the buttons and read the output. Notice that hx-get puts the parameter in the URL, while a form hx-post sends it in the body, and that HTMX always adds an HX-Request: true header, which is how real servers recognize an HTMX call.

Routes, query, form and headers

(The &amp; in the URL is just how you write & correctly inside an HTML attribute.)

Alpine needs no stub

Alpine.js never talks to a server by itself, so it needs no mock. You add the one defer script tag and write directives. A quick check that both libraries are alive on a page is to print their version numbers:

Check that both libraries loaded

If you ever see "checking..." stay on screen, one of the scripts failed to load. Open the browser's developer tools and look at the Network and Console tabs.

Using the libraries in a real project

The CDN tags are perfect for learning and for small sites. In a larger project you have three common options:

  • Keep the CDN tags. Simple and fast, and the file is cached across sites. Pin the version.
  • Install with npm. Run npm install htmx.org alpinejs, then import them in your entry file. For Alpine you write import Alpine from 'alpinejs'; window.Alpine = Alpine; Alpine.start();, and for HTMX import 'htmx.org' plus window.htmx = htmx if you want the global.
  • Self-host the files. Copy htmx.min.js and cdn.min.js into your public folder, so your site has no third-party runtime dependency.

In every case, delete the mock server and let your backend answer. For the server side, see Server-Side Setup.

Subresource integrity (read-only)

When you load a script from a CDN you trust the CDN not to change it. Subresource Integrity (SRI) lets the browser verify the file against a hash you provide, and refuse it if it differs. The tag looks like this (the hash here is a placeholder, not a real value):

HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/htmx.min.js"
        integrity="sha384-PLACEHOLDER-HASH-FROM-YOUR-OWN-DOWNLOAD"
        crossorigin="anonymous"></script>

Generate the real value yourself by hashing the exact file you downloaded, for example with openssl dgst -sha384 -binary htmx.min.js | openssl base64 -A. SRI only makes sense on a pinned URL, because any change to the file breaks the hash. Our live examples skip SRI so they stay short.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the Alpine.js CDN script loaded with defer?

    The deferred script runs once the document is parsed, so Alpine's first scan sees all of your x-data elements.
  2. 2. What does the mock server replace?

    htmx is real in these examples. Only the object that would normally use the network is faked.
  3. 3. A handler is registered with server("GET", "/hello", fn). What happens on a request to /missing?

    An unregistered path produces a 404 reply. htmx only swaps successful responses unless you configure it otherwise.
  4. 4. What is the main benefit of pinning [email protected] instead of htmx.org@latest?

    A pinned version never changes underneath you, so upgrades happen only when you decide.

Summary

  • Add htmx.min.js normally and the Alpine cdn.min.js with defer; pin exact versions (htmx 2.0.4, Alpine 3.14.8 here).
  • HTMX needs a server. In the sandbox, a small stub replaces XMLHttpRequest and answers from routes registered with server(method, path, handler).
  • A handler receives { query, form, headers } and returns an HTML string or { status, body, headers }.
  • Alpine needs no mock; it only runs in the browser.
  • In real projects, remove the stub, and consider npm or self-hosting. SRI hashes protect pinned CDN files.

Continue with Reactive State with x-data.