HTMS šØ Stream Async HTML, Stay SEO-Friendly
npm install htms-jshtms-js is an early-stage project: a proposal to progressively render HTML with async functions, while staying SEO-friendly and lightweight. It's not meant as _the new default_, but as an alternative that can fit into many stacks or frameworks.
data-htms.
bash
$ curl -N https://htms.skarab42.dev/curl
`

$3

---
š Quick start
$3
Use your preferred package manager to install the plugin:
`bash
pnpm add htms-js
`
$3
`html
News feed
Loading newsā¦
User profile
Loading profileā¦
`
$3
`js
// home-page.js
export async function loadNews() {
await new Promise((r) => setTimeout(r, 100));
return ;
}
export async function loadProfile() {
await new Promise((r) => setTimeout(r, 200));
return ;
}
`
$3
`js
import { Writable } from 'node:stream';
import Express from 'express';
import { createHtmsFileModulePipeline } from 'htms-js';
const app = Express();
app.get('/', async (_req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
await createHtmsFileModulePipeline('./home-page.html').pipeTo(Writable.toWeb(res));
});
app.listen(3000);
`
Visit http://localhost:3000: content renders immediately, then fills itself in.
$3
When you call createHtmsFileModulePipeline('./home-page.html'), HTMS will automatically look for a sibling module file named ./home-page.js and resolve tasks from there. If you want to:
- Mix several modules on the same page ā see Scoped modules.
- Point to another file ā use the specifier option in the API.
- Provide your own logic ā see Custom resolvers.
---
Examples
- Express, Fastify, Hono
- Raw streaming (stdout)
- htms server (cli)
`bash
git clone https://github.com/skarab42/htms-js.git
cd htms-js
pnpm i && pnpm build
`
`bash
run from repo root, pick one:
pnpm --filter server-example start # published dashboard demo at https://htms.skarab42.dev
pnpm --filter hono-example start
pnpm --filter fastify-example start
pnpm --filter express-example start
pnpm --filter stdout-example start
`
---
HTMS attributes
> You can omit the data- prefix, though using it is more in line with standard HTML practices.
$3
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.
`html
loading task A from 'root-module.js'...
loading task A from 'child-module.js'...
loading task A from 'child-module.js'...
loading task A from 'root-module.js'...
loading task B from 'root-module.js'...
loading task B from 'child-module.js'...
`
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.
$3
`html
`
$3
`ts
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'
}
`
$3
- 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) where value is an object/array.
Commit behavior (
data-htms-commit)
Controls how the streamed result is applied to the placeholder. Default: replace.
| Value | Effect | DOM equivalent | Accessibility (aria-busy) |
| --------- | --------------------------------------------------- | ---------------------------- | --------------------------- |
| replace | Replace the placeholder node (outer) | host.replaceWith(frag) | No |
| content | Replace the children of the placeholder (inner) | host.replaceChildren(frag) | Yes |
| append | Append result as last child | host.append(frag) | Yes |
| prepend | Insert result as first child | host.prepend(frag) | Yes |
| before | Insert result before the placeholder | host.before(frag) | No |
| after | Insert result after the placeholder | host.after(frag) | No |
HTML examples
Assuming the streamed content is:
`html
Loadingā¦
Streamed
Loadingā¦
Streamed
Existing
Existing
Streamed
Existing
Streamed
Existing
Streamed
Streamed
`
Notes
- With append, prepend, before, after, the placeholder stays in the DOM.
- With content, append, or prepend, the container is kept (useful for accessibility/live regions).
$3
When data-htms-commit="content", append, or prepend is used, HTMS automatically marks the placeholder as a polite live region while it is pending:
- Adds role="status" and aria-busy="true" on the host before the first update.
- On the first update, sets aria-busy="false", so screen readers announce the content as soon as it arrives.
- Screen readers will announce any further chunks (additional updates) directly, since aria-busy stays false.
This gives you accessible announcements out of the box, without extra markup.
Tips for accessibility:
- If accessibility is a priority, avoid too many updates: prefer a single update ("one shot") if the task is fast enough to prevent excessive announcements.
---
Task API:
api.commit(...)
Use api.commit(html, options?) inside a task to push partial updates before the final return.
Minimal shape (JS):
`js
// In a task: (value, api) => Promise
// default mode when options are omitted: 'append'
api.commit('chunk');
api.commit('chunk', { mode: 'append' }); // mode: 'content' | 'append' | 'prepend' | 'before' | 'after'
`
Type definitions (TypeScript):
`ts
export type CommitMode = 'replace' | 'content' | 'append' | 'prepend' | 'before' | 'after';
export interface TaskApiOptions {
// Optional. If omitted, commit defaults to mode: 'append'.
mode?: Exclude;
}
export interface TaskApi {
// 'replace' is not allowed for partial commits:
// the host's UUID anchors subsequent updates; replacing the host would break future commits.
commit(html: string, options?: TaskApiOptions): void;
}
export type Task = (value: Value, api: TaskApi) => PromiseLike;
`
Rules:
- Allowed modes: content, append, prepend, before, after (not replace).
- Default mode for partial commits when options are omitted: append.
- Why not replace: partial commits must target the original host by UUID; replacing the host would drop that anchor and break subsequent commits.
- Each api.commit(...) emits a partial chunk applied immediately on the client.
- The final HTML is the taskās return value and uses the hostās data-htms-commit. With data-htms-commit="append", returning '' performs no DOM change (just cleanup).
Example (stream items with append):
`html
- Loadingā¦
`
`js
// tasks.js
export async function loadFeed(_value, api) {
// Clear the placeholder once (optional if already empty)
api.commit('', { mode: 'content' });
// Any async iterable of items
for await (const item of getFeedAsyncIterable()) {
// options omitted ā defaults to 'append'
api.commit();
}
// Final empty return with host commit="append" ā no DOM change, just cleanup
return '';
}
`
Notes:
- Fragments must be wellāformed HTML. Use the host as the container; donāt stream unbalanced tags.
- content, append, and prepend automatically manage live-region ARIA. If you need announcements, use these modes.
---
Under the hood (advanced)
A classic htms pipeline.
`ts
import process from 'node:process';
import { Writable } from 'node:stream';
import {
createFileStream,
createHtmsResolver,
createHtmsSerializer,
createHtmsTokenizer,
ModuleResolver,
} from 'htms-js';
const resolver = new ModuleResolver('./tasks.js');
await createFileStream('./index.html')
.pipeThrough(createHtmsTokenizer())
.pipeThrough(createHtmsResolver(resolver))
.pipeThrough(createHtmsSerializer())
.pipeTo(Writable.toWeb(process.stdout));
`
Works anywhere with a WritableStream: File, HTTP, network, stdout, ...
$3
`ts
// Streams
createStringStream(input: string | string[]): ReadableStream
createFileStream(filePath: string): ReadableStream
// Core transforms
createHtmsTokenizer(): TransformStream
createHtmsResolver(resolver: Resolver): TransformStream
createHtmsSerializer(): TransformStream
createHtmsCompressor(encoding: Encoding): TransformStream
// Pipelines
createHtmsStringPipeline(html: string, resolver: Resolver): ReadableStream
createHtmsFilePipeline(filePath: string, resolver: Resolver): ReadableStream
createHtmsStringModulePipeline(html: string, moduleSpecifier: string): ReadableStream
createHtmsFileModulePipeline(filePath: string, opts?: { specifier?: string; extension?: string }): ReadableStream
`
---
API
$3
`ts
createHtmsFileModulePipeline(
filePath: string,
options?: {
specifier?: string;
extension?: string;
basePath?: string;
cacheModule?: boolean;
}
): ReadableStream
`
- filePath: path to HTML with placeholders.
- options.specifier: relative module path.
- options.extension: auto-derive tasks module by swapping extension (default: js).
- options.basePath: module base path.
- options.cacheModule: enable module caching.
$3
- Uses require.resolve + dynamic import.
- Supports .ts, .mts, .cts if your runtime allows it.
- Task names = HTML placeholders.
- Named exports or a default export object are valid.
---
Custom resolvers
A resolver follows the minimal Resolver contract. It doesn't run tasks, only returns a function the serializer will call.
`ts
export type Task = () => PromiseLike;
export interface TaskInfo {
name: string;
uuid: string;
}
export interface Resolver {
resolve(info: TaskInfo): Task | Promise;
}
`
$3
`ts
import { createFileStream, createHtmsTokenizer, createHtmsResolver, createHtmsSerializer } from 'htms-js';
import { Writable } from 'node:stream';
class MapResolver {
#map = new Map Promise>([
[
'foo',
async () => {
await new Promise((r) => setTimeout(r, 200));
return 'Foo ā';
},
],
[
'bar',
async () => {
await new Promise((r) => setTimeout(r, 400));
return 'Bar ā';
},
],
]);
resolve(info: { name: string }) {
const task = this.#map.get(info.name);
if (!task) {
return () => Promise.reject(new Error( Unknown task: ${info.name}));
}
return task;
}
}
await createFileStream('./index.html')
.pipeThrough(createHtmsTokenizer())
.pipeThrough(createHtmsResolver(new MapResolver()))
.pipeThrough(createHtmsSerializer())
.pipeTo(Writable.toWeb(process.stdout));
`
$3
- resolve(info) can return a Task or Promise.
- A Task must return a string (HTML) or a promise resolving to one.
- Prefer returning a rejecting task over throwing inside resolve()`.