fastify-htms
v0.9.0
Published
HTMS 💨 Stream Async HTML, Stay SEO-Friendly
Downloads
19
Readme
fastify-htms
Fastify plugin that integrates htms-js with Fastify.
Try the live demo
- https://htms.skarab42.dev
Install
Use your preferred package manager to install the plugin:
pnpm add fastify fastify-htmsPrerequisite
Before starting the server, you need at least one HTML file and a module that exports functions used by HTMS placeholders. These functions will be called to progressively fill in the HTML while it streams.
Example setup:
<!-- ./public/index.html -->
<!doctype html>
<html lang="en">
<body>
<h1>News feed</h1>
<div data-htms="loadNews">Loading news…</div>
<h1>User profile</h1>
<div data-htms="loadProfile">Loading profile…</div>
</body>
</html>// ./public/index.js
export async function loadNews() {
await new Promise((r) => setTimeout(r, 100));
return `<ul><li>Breaking story</li><li>Another headline</li></ul>`;
}
export async function loadProfile() {
await new Promise((r) => setTimeout(r, 200));
return `<div class="profile">Hello, user!</div>`;
}When you run the server, htms-js will scan the HTML for elements with data-htms attributes, then dynamically import the functions from the matching module (index.js) to resolve and stream the content.
Scoped modules
HTMS supports scoped modules, meaning tasks can resolve from different modules depending on context. You can nest modules and HTMS will pick the right scope for each placeholder.
<section data-htms-module="root-module.js">
<div data-htms="taskA">loading task A from 'root-module.js'...</div>
<div data-htms="taskA" data-htms-module="child-module.js">loading task A from 'child-module.js'...</div>
<div data-htms-module="child-module.js">
<div data-htms="taskA">loading task A from 'child-module.js'...</div>
<div data-htms="taskA" data-htms-module="root-module.js">loading task A from 'root-module.js'...</div>
</div>
<div data-htms="taskB">loading task B from 'root-module.js'...</div>
<div data-htms="taskB" data-htms-module="child-module.js">loading task B from 'child-module.js'...</div>
</section>This makes it easier to compose and reuse modules without conflicts.
Task value (data-htms-value)
data-htms-value passes one argument to the task.
When present, the value is parsed as JSON5 and given to the task as its first parameter.
If the attribute is omitted, the task receives undefined.
- Accepted:
undefined,null, booleans, numbers, strings, arrays, objects (JSON5: single quotes, unquoted keys, comments, trailing commas). - Not accepted: functions, arbitrary JS expressions.
- Need multiple pieces of data? Pack them into one object or array.
HTML examples
<!-- attribute omitted → value = undefined -->
<div data-htms="loadDefaults"></div>
<!-- primitive values -->
<div data-htms="loadDefaults" data-htms-value="null"></div>
<div data-htms="loadProfile" data-htms-value="true"></div>
<div data-htms="loadUser" data-htms-value="12345"></div>
<div data-htms="loadByName" data-htms-value="'john-doe'"></div>
<!-- object / array (JSON5) -->
<div data-htms="loadFeed" data-htms-value="{ theme: 'compact', limit: 10 }"></div>
<div data-htms="renderOffer" data-htms-value="[42, { theme: 'compact' }]"></div>Task signatures (TypeScript examples)
export async function loadDefaults(value: undefined | null) {}
export async function loadProfile(value: boolean) {}
export async function loadUser(value: number) {}
export async function loadByName(value: string) {}
export async function loadFeed(value: { theme: string; limit: number }) {
// value.theme === 'compact'
// value.limit === 10
}
export async function renderOffer(value: [number, { theme: string }]) {
const [offerId, options] = value;
// offerId === 42
// options.theme === 'compact'
}Tips
- Keep it serializable. Only data you could express in JSON5 should go here.
- Prefer objects when the meaning of fields matters:
{ id, page, sort }is clearer than[id, page, sort]. - Strings must be quoted. Use JSON5 single quotes in HTML to stay readable.
- Validate inside the task. Treat the value as untrusted input.
- One argument by design. If you need several inputs, bundle them:
(value)wherevalueis an object/array.
Commit behavior (data-htms-commit)
Controls how the streamed result is applied to the placeholder. Default: replace.
| Value | Effect | DOM equivalent |
| --------- | --------------------------------------------------- | ---------------------------- |
| replace | Replace the placeholder node (outer) | host.replaceWith(frag) |
| content | Replace the children of the placeholder (inner) | host.replaceChildren(frag) |
| append | Append result as last child | host.append(frag) |
| prepend | Insert result as first child | host.prepend(frag) |
| before | Insert result before the placeholder | host.before(frag) |
| after | Insert result after the placeholder | host.after(frag) |
HTML examples
Assuming the streamed content is: <div>Streamed</div>
<!-- replace (default): host node is replaced by the content -->
<div data-htms="getUser" data-htms-commit="replace">Loading…</div>
<!-- becomes -->
<div>Streamed</div>
<!-- content: keep the host, swap its children -->
<div data-htms="getUser" data-htms-commit="content">Loading…</div>
<!-- becomes -->
<div><div>Streamed</div></div>
<!-- append: add at the end of host -->
<section data-htms="getUser" data-htms-commit="append"><div>Existing</div></section>
<!-- becomes -->
<section>
<div>Existing</div>
<div>Streamed</div>
</section>
<!-- prepend: add at the beginning of host -->
<section data-htms="getUser" data-htms-commit="prepend"><div>Existing</div></section>
<!-- becomes -->
<section>
<div>Streamed</div>
<div>Existing</div>
</section>
<!-- before: insert before the host -->
<hr data-htms="getUser" data-htms-commit="before" />
<!-- becomes -->
<div>Streamed</div>
<hr />
<!-- after: insert after the host -->
<hr data-htms="getUser" data-htms-commit="after" />
<!-- becomes -->
<hr />
<div>Streamed</div>Notes
- With
append,prepend,before,after, the placeholder stays in the DOM. Remove or restyle it if needed once the chunk is committed. - With
content, you keep the container (useful for accessibility/live regions).
Accessibility (content mode)
When data-htms-commit="content" is used, HTMS automatically marks the placeholder as a polite live region while it is pending:
- Adds
role="status"andaria-busy="true"on the host before the first update. - On commit, flips
aria-busytofalseso screen readers announce the final content once.
This gives you accessible announcements out of the box, without extra markup. If you need a different behavior, switch to another commit mode or set your own ARIA attributes on the host.
Usage
import Fastify from 'fastify';
import fastifyHtms from 'fastify-htms';
const app = Fastify();
app.register(fastifyHtms, {
root: './public',
index: 'index.html',
match: '**/*.html',
});
app.listen({ port: 3000 });This will:
- Look for
.htmlfiles under the givenroot - Stream them through the HTMS pipeline
- Serve
index.htmlwhen the path is a directory - Return 404 if no match is found
To also serve static assets (images, css, js), register @fastify/static alongside this plugin.
Options
| Option | Type | Default | Description |
| ---------------- | -------------------------------- | --------------------------- | ----------------------------------------------------------- |
| root | string | | Required. Folder that contains your .html files |
| index | string | 'index.html' | Default file to serve when a directory is requested |
| match | string | '**/*.htm?(l)' | Minimatch pattern to filter which files are handled by HTMS |
| environment | 'development' \| 'production' | 'development' | Set the environment |
| compression | boolean | true | Enable response compression |
| encodings | HtmsCompressorEncoding | ['br', 'gzip', 'deflate'] | Enable response compression |
| cacheModule | boolean | true | Enable module caching |
| createResolver | (filePath: string) => Resolver | undefined | Custom resolver factory for HTMS |
More info
For details on how HTMS works and how to write resolvers, see htms-js.
Status
This is experimental. APIs may change.
We'd love developers to:
- Experiment in different contexts.
- Find limits: performance, DX, compatibility.
- Challenge assumptions and suggest alternatives.
- See if it fits your framework or stack.
Contribute
Help explore whether streaming HTML can be practical:
The only way to know where this works or breaks is to try it together.
License
MIT
