Repository navigation
Install into an existing app
This page adds STomp to a site or server you already have. It covers what to install, how to serve STomp's files from Express, plain node:http, nginx, Caddy, a static host or Vite, where the wisp server comes from, and how your page loads the controller.
If you are starting from nothing, Bootstrapper quickstart is shorter. Building the browser UI itself (tabs, history buttons, popups) is on Embed STomp in your site.
Every setup on this page was run against @sysce/stomp@4.2.0-nightly.202611192242.ge5f74c5 in headless Chrome 157, loading a real site through the proxy.
| Piece | Package | Runs in | Served at (on this page) |
|---|---|---|---|
| STomp |
@sysce/stomp (stompPath is its dist/) |
your page, the service worker, the proxied pages, a few workers | /stomp/ |
| Transport |
@mercuryworkshop/epoxy-transport (Fracital build) or @mercuryworkshop/libcurl-transport
|
a dedicated worker the controller starts |
/epoxy/, /libcurl/
|
| Wisp server |
holywisp or @mercuryworkshop/wisp-js, or the public relay |
your server, or none |
/wisp/ (WebSocket) |
A request from a proxied page goes: the page, then the service worker (which rewrites what comes back), then the transport, then the wisp server, then the real site. The transport makes the TLS connection to the site itself, in the browser. The wisp server relays TCP and UDP streams, so for an HTTPS site it only ever sees encrypted bytes.
The controller (StompController) lives in your page and connects the service worker to the transport. It has to stay open for the proxied frames to work: a proxied page with no live controller gets no answers.
- A secure context: HTTPS, or
localhostduring development. On plain HTTP anywhere else the browser has nonavigator.serviceWorker, andStompController.register()throwsYour browser does not support service workers. - STomp's files on the same origin as the page that creates the controller. The constructor throws
Stomp directory must be same-originotherwise. To put proxied pages on another origin, useRemoteController(Origin isolation). - Node.js 22 or newer for the server examples (
@sysce/stompdeclares"node": ">=22"). - Access to github.com from wherever you run
npm install: npm downloads the Fracital epoxy build from GitHub as a tarball. git itself is not needed (checked with npm 10.9 and 11.19).
npm install -E @sysce/stomp@nightly
npm install -E "@mercuryworkshop/epoxy-transport@$(npm view @sysce/stomp@nightly "devDependencies[@mercuryworkshop/epoxy-transport]")"
# a wisp server, if your server will run one
npm install -E holywispPin exact versions. -E writes "@sysce/stomp": "4.2.0-nightly.202611192242.ge5f74c5" instead of a ^ range. A range on a prerelease still lets npm pick a newer nightly, and each nightly is a new build of master. When you upgrade, change the version on purpose and test again.
Give the @nightly tag (or an exact nightly version). The latest tag still points at 2.0.0 from 2023, the Bare-server STomp with the StompBoot API; Migrating from TOMP describes it.
Use the epoxy build STomp pins, not @mercuryworkshop/epoxy-transport from npm. The npm release resets HTTP/2 responses whose headers exceed 16 KiB (YouTube's do), loses one of two requests started together on a cold transport, and hangs on a pooled connection the server already closed. The pinned build patches these; deploy/epoxy/README.md lists every patch. The npm view command above reads the pin from the STomp version you install: for 4.2.0-nightly.202611200512.g041dc67 it is github:Fracital/EpoxyTransport#4d5a277e0e7691e572633d829c17619c2ef647b3. If you pin an older STomp, run it with that version in place of nightly.
@mercuryworkshop/libcurl-transport from npm works too (npm install -E @mercuryworkshop/libcurl-transport). Transports and Wisp says when to pick which.
Serve the whole of stompPath under one directory of your site. This page uses /stomp/; any path works if you pass the same one to the controller. The controller and the service worker request files from that directory by name while they run (workers, wasm modules, the inject bundles), so a file you leave out fails later, not at startup. rewriterLib.js is one every host needs: without it controller.wait() rejects with an error that names it.
What the server has to get right:
-
.jsand.mjsas JavaScript. Browsers refuse to run module scripts and worker scripts served with any other type. -
.wasmasapplication/wasm. When the type is wrong, STomp's own wasm loader downloads the file a second time and compiles it without streaming, which is slower. - The directory path ends with a slash, in the URL you mount and in the string you give the controller.
Some files are requested with a query of 16 hex digits, the hash of their bytes (transportWorker.js? and the hash, for example). A static server ignores the query, which is what you want. Deploy STomp covers caching them.
STomp needs no special response headers. If you want proxied pages that ask for cross-origin isolation (SharedArrayBuffer, the precise clock) to get it, your page and these files need Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy; Deploy STomp has the details.
The transport is a separate package and is served on its own path. Serve its whole dist/: epoxy loads epoxy.wasm and h3/ next to index.mjs.
import { createServer } from 'node:http';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import express from 'express';
import { holyWisp } from 'holywisp';
import { stompPath } from '@sysce/stomp/path';
// the directory of a package's entry file (its dist/)
const distOf = (name) => dirname(fileURLToPath(import.meta.resolve(name)));
const wisp = new holyWisp();
await wisp.start(1);
const app = express();
app.use('/stomp/', express.static(stompPath));
app.use('/epoxy/', express.static(distOf('@mercuryworkshop/epoxy-transport')));
// ...your own routes and static files...
app.use(express.static('public'));
const server = createServer(app);
server.on('upgrade', (req, socket, head) => {
if (req.url.startsWith('/wisp/')) wisp.route(req, socket, head);
else socket.destroy();
});
server.listen(Number(process.env.PORT) || 8080, () =>
console.log(`http://localhost:${server.address().port}/`),
);Express's static handler sends the right types for .mjs and .wasm. If you use libcurl, serve it the same way: app.use('/libcurl/', express.static(distOf('@mercuryworkshop/libcurl-transport'))).
@sysce/stomp/path is a CommonJS module, and the named import above works from an ES module. From CommonJS, const { stompPath } = require('@sysce/stomp/path').
No framework, and a different wisp server (wisp-js) to show that any wisp server works:
npm install -E @mercuryworkshop/wisp-jsimport { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises';
import { createServer } from 'node:http';
import { dirname, extname, join, normalize, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { server as wisp } from '@mercuryworkshop/wisp-js/server';
import { stompPath } from '@sysce/stomp/path';
const distOf = (name) => dirname(fileURLToPath(import.meta.resolve(name)));
// URL prefix -> directory on disk; the first prefix that matches answers
const mounts = [
['/stomp/', stompPath],
['/epoxy/', distOf('@mercuryworkshop/epoxy-transport')],
['/', fileURLToPath(new URL('./public/', import.meta.url))],
];
const types = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json',
'.wasm': 'application/wasm',
'.css': 'text/css; charset=utf-8',
'.map': 'application/json',
};
async function serveStatic(req, res) {
const { pathname } = new URL(req.url, 'http://localhost');
const [prefix, root] = mounts.find(([prefix]) => pathname.startsWith(prefix));
try {
let file = normalize(
join(root, decodeURIComponent(pathname.slice(prefix.length))),
);
if (file.startsWith(join(root, sep)) || file === root) {
let info = await stat(file);
if (info.isDirectory()) {
file = join(file, 'index.html');
info = await stat(file);
}
res.writeHead(200, {
'Content-Type': types[extname(file)] ?? 'application/octet-stream',
'Content-Length': info.size,
'Cache-Control': 'no-cache',
});
if (req.method === 'HEAD') return res.end();
return createReadStream(file).pipe(res);
}
} catch {
// a bad escape or no such file: answer 404
}
res.writeHead(404, { 'Content-Type': 'text/plain' }).end('Not found');
}
const server = createServer((req, res) => {
if (req.method !== 'GET' && req.method !== 'HEAD')
return res.writeHead(405).end();
serveStatic(req, res);
});
server.on('upgrade', (req, socket, head) => {
if (req.url.startsWith('/wisp/')) wisp.routeRequest(req, socket, head);
else socket.destroy();
});
server.listen(Number(process.env.PORT) || 8080, () =>
console.log(`http://localhost:${server.address().port}/`),
);The startsWith(join(root, sep)) check refuses paths such as /stomp/%2e%2e/package.json that would leave the mounted directory. With Fastify, Koa or Hono on Node the idea is the same: a static handler on stompPath and the raw (req, socket, head) of the upgrade event passed to the wisp server.
nginx serves files well, and its stock mime.types has no entry for .mjs (checked on nginx 1.30.7). It then sends controller.mjs and the epoxy module as application/octet-stream, the browser refuses to run them as modules, and nothing starts. Add a type for .mjs:
server {
listen 8080;
root /srv/site; # your site, with STomp's dist/ copied to /srv/site/stomp/
# nginx's mime.types has no entry for .mjs, and a browser runs a module
# script only when it is served as JavaScript
location ~ \.mjs$ {
types { }
default_type text/javascript;
}
# the wisp WebSocket, relayed to the Node server that runs holyWisp
location /wisp/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 1h;
}
}Copy the files in at build or deploy time:
cp -r node_modules/@sysce/stomp/dist /srv/site/stomp
cp -r node_modules/@mercuryworkshop/epoxy-transport/dist /srv/site/epoxyThe /wisp/ block forwards the WebSocket upgrade to a Node process running holyWisp (the Express server above, on port 3000 here). Without Upgrade and Connection the upgrade never reaches it. proxy_read_timeout keeps a quiet wisp connection from being closed after nginx's default 60 seconds. If you use the public relay instead, leave the block out. HTTPS, headers and caching for production are on Deploy STomp.
Caddy sends .mjs as JavaScript and forwards WebSocket upgrades without extra settings:
:8080 {
root * /srv/site
# the wisp WebSocket, relayed to the Node server that runs holyWisp
reverse_proxy /wisp/* 127.0.0.1:3000
file_server
}
Copy the files in the same way as for nginx. Checked with Caddy 2.11.4.
STomp needs no server code of its own. Any static host that serves the files with the types above works: copy dist/ to stomp/ and the epoxy dist/ to epoxy/ in your published folder, and point the transport at a wisp server somewhere else, for example the public relay (see Pick a wisp server). This was checked with python3 -m http.server (Python 3.14 sends .mjs as text/javascript) and wss://holywisp.fracit.al/.
The host has to serve the site over HTTPS for anyone but you, as for every service worker.
In a Vite app you can import the controller from the package and let Vite bundle it. The service worker and the workers still have to be served as files, so copy stompPath and the epoxy dist/ into the build with vite-plugin-static-copy, and run holyWisp from its Vite plugin during vite and vite preview:
npm install -E @sysce/stomp@nightly
npm install -E "@mercuryworkshop/epoxy-transport@$(npm view @sysce/stomp@nightly "devDependencies[@mercuryworkshop/epoxy-transport]")"
npm install -D vite vite-plugin-static-copy holywispvite.config.js:
import { createRequire } from 'node:module';
import { dirname } from 'node:path';
import { holyWispVite } from 'holywisp/vite';
import { defineConfig, normalizePath } from 'vite';
import { viteStaticCopy } from 'vite-plugin-static-copy';
const require = createRequire(import.meta.url);
const { stompPath } = require('@sysce/stomp/path');
const epoxyPath = dirname(require.resolve('@mercuryworkshop/epoxy-transport'));
export default defineConfig({
plugins: [
// STomp's dist/ at /stomp/ and epoxy's dist/ at /epoxy/, in dev and in the build
viteStaticCopy({
targets: [
{ src: normalizePath(`${stompPath}/*`), dest: 'stomp', rename: { stripBase: true } },
{ src: normalizePath(`${epoxyPath}/*`), dest: 'epoxy', rename: { stripBase: true } },
{ src: normalizePath(`${epoxyPath}/h3/*`), dest: 'epoxy/h3', rename: { stripBase: true } },
],
}),
// a wisp server on /wisp/ for `vite` and `vite preview`
holyWispVite({ path: '/wisp/', apply: 'both' }),
],
});main.js, loaded from index.html with <script type="module" src="/main.js"></script>:
import { SearchBuilder, StompController } from '@sysce/stomp';
const form = document.getElementById('stomp-form');
const input = document.getElementById('stomp-input');
const search = new SearchBuilder('https://duckduckgo.com/?q=%s');
const ready = (async () => {
const directory = '/stomp/';
const registration = await StompController.register(directory);
const controller = new StompController({
serviceworker: registration,
transport: {
module: '/epoxy/index.mjs',
options: [{ wisp: location.origin.replace(/^http/, 'ws') + '/wisp/' }],
},
directory,
onNavigate(info) {
input.value = info.url;
},
});
await controller.wait();
return controller.createFrame(document.getElementById('stomp-frame'));
})();
form.addEventListener('submit', async (event) => {
event.preventDefault();
const frame = await ready;
frame.go(search.query(input.value));
});Checked with Vite 8.3.8 and vite-plugin-static-copy 4.1.1, in vite and in vite build followed by vite preview. Three details in the config:
-
rename: { stripBase: true }puts the files directly understomp/andepoxy/. Version 4 of the plugin keeps the source's directory structure by default, which would serve them under/stomp/node_modules/@sysce/stomp/dist/instead, and Vite's HTML fallback would then answer/stomp/serviceWorker.jswith yourindex.html. -
stripBase: trueflattens every directory, so epoxy'sh3/folder gets a target of its own. -
holyWispViteonly runs in the dev and preview servers. A production build is static files: serve it like any static site and run a wisp server (or use the public relay) next to it.
The controller Vite bundles into your app and the dist/ files you copy come from the same package version, so they are one build. Do not mix a bundled controller from one version with dist/ files from another: the controller then reports itself stale (Embed STomp in your site).
The directory you serve dist/ from is also the service worker's scope. StompController.register('/stomp/') registers /stomp/serviceWorker.js with the scope /stomp/, so you never need a Service-Worker-Allowed header. Every proxied address lives under it: /stomp/<controller id>/<kind>/<sealed URL>.
- Your page does not have to be inside the scope. The quickstart page is at
/and works. - Keep your own pages out of the scope. A page of yours under
/stomp/would be controlled by STomp's worker. - A site-wide service worker of your own (scope
/) can stay. The browser picks the registration with the longest matching scope, so STomp's controls/stomp/and yours controls the rest. Do not register STomp's worker at/. - Several controllers can share one directory (two tabs of your app, for example). They share its cookie jar, HTTP cache and storage, as tabs of one browser do.
-
register()setsupdateViaCache: 'none', so the browser checks the worker script on every update check instead of using a cached copy. How deploys reach running tabs is on Deploy STomp.
The transport needs a wisp server to reach the internet. The wisp URL is the transport's wisp option.
| Option | When | What you run |
|---|---|---|
| holyWisp | your server runs Node; the same relay as stomp.fracit.al |
npm install holywisp, new holyWisp(), await wisp.start(1), wisp.route(req, socket, head) on upgrade
|
| wisp-js | you want a server written in JavaScript |
npm install @mercuryworkshop/wisp-js, wisp.routeRequest(req, socket, head) on upgrade
|
| the public relay | a static host, or a quick test | nothing; wisp: 'wss://holywisp.fracit.al/'
|
holyWisp (Fracital/holyWisp) is a wisp server written in C. The holywisp npm package carries prebuilt binaries for Linux, macOS and Windows on x64 and arm64, starts one as a child process on a free loopback port and stops it when Node exits. start(n) takes the number of worker threads (0 for one per CPU). Its egress defaults refuse loopback and private addresses; allowLoopbackIPs and allowPrivateIPs open them, which gives every visitor access to your machine and network. Behind a reverse proxy, list the proxy in trustedProxies so per-client limits see real client addresses. The package README has every option.
wisp-js 0.5.3 also refuses loopback and private addresses by default (allow_loopback_ips and allow_private_ips in wisp.options).
The public relay at wss://holywisp.fracit.al/ is the holyWisp instance the demo uses. It accepted connections from a page on http://localhost and on a static host in testing. The sites you visit see the relay's IP address, not yours.
On an HTTPS page the wisp URL must be wss://; the browser blocks ws:// from a secure page. Deriving it from location.origin, as the examples here do, gets this right on both.
transport takes either a descriptor or a constructed transport.
| You pass | Example | Where it runs | controller.transportHost |
|---|---|---|---|
| a descriptor | { module: '/epoxy/index.mjs', options: [{ wisp }] } |
a dedicated worker the controller starts from transportWorker.js
|
'worker' |
a descriptor with host: 'page'
|
{ module: '/epoxy/index.mjs', options: [{ wisp }], host: 'page' } |
your page | 'page' |
| an instance | new EpoxyTransport({ wisp }) |
your page | 'page' |
Use a descriptor. A transport in your page's main thread cannot answer while that thread is blocked, and a proxied page's synchronous XHR blocks it while waiting for the network. In a worker it is answered.
The descriptor's module is an ES module URL whose default export is the transport class; the controller runs new Module(...options). Epoxy's and libcurl's dist/index.mjs both qualify. For libcurl, raise the connection pool the way the demo does, because libcurl.js 0.7's default pool stalls on pages that make many requests:
transport: {
module: '/libcurl/index.mjs',
options: [{ wisp, connections: [500, 400, 200] }],
},If the worker cannot start or cannot import the module, the controller imports it in the page instead and dispatches a transporthost event with detail: { host: 'page', error }. controller.setTransport(descriptor) swaps the transport while the controller runs. HTTP/3, shards and the full option list are on Transports and Wisp.
Three ways, all checked. Each gives you StompController and SearchBuilder.
An ES module from the served directory, no build step:
<script type="module">
import { StompController, SearchBuilder } from '/stomp/controller.mjs';
</script>Classic scripts, which define globals:
<script src="/stomp/Controller.js"></script>
<script src="/stomp/SearchBuilder.js"></script>
<script>
// StompController, StompRemoteController and SearchBuilder are globals now
</script>Controller.js defines StompController and StompRemoteController; SearchBuilder is in its own file.
A bundler (Vite, webpack, esbuild):
import { StompController, SearchBuilder } from '@sysce/stomp';The package ships TypeScript declarations (dist/types/). A bundled controller still needs dist/ served, as in the Vite section.
Pass directory to both register() and the constructor even though it has a default. The default is the directory of document.currentScript, which only exists while a classic script first runs; from a module, a bundle or a callback it is the directory of your page, which is rarely where dist/ is.
In the browser's developer tools:
- Application, Service workers: a worker
serviceWorker.jswith the scopehttps://your.site/stomp/, activated and running. - Network: a WebSocket to your wisp URL once the first page loads. With a descriptor transport it is opened by the transport worker.
- The proxied frame's address looks like
/stomp/kDqSTAdH/html/rffNfPYzd0_xQnlDqhsldqEiVA. - In the console, with your controller in a variable:
controller.transportHostis'worker',controller.idis the 8-character id in those addresses, andcontroller.staleisnull.
The page is not a secure context. Serve it over HTTPS, or use localhost while developing. A LAN address such as http://192.168.1.23 does not count.
The server sends .mjs as something other than JavaScript. nginx does by default; see nginx.
The worker script is not where register() looks. It requests <directory>serviceWorker.js. Check that the directory ends with a slash and that the server mounts dist/ at exactly that path.
directory names another origin. A StompController serves everything from your page's origin. For a second origin, use RemoteController (Origin isolation).
rewriterLib.js is not served from the directory. Serve all of dist/.
A single-page app fallback answers paths it does not know with index.html. Mount STomp's files before the fallback. In Vite, this happens when the copy plugin puts the files somewhere other than /stomp/; see the stripBase note in Vite.
The transport cannot reach the wisp server. Look for the WebSocket to your wisp URL in the Network panel. Behind nginx or another reverse proxy, the proxy has to forward the Upgrade and Connection headers. On an HTTPS page, a ws:// wisp URL is blocked as mixed content.
Both holyWisp and wisp-js refuse loopback and private addresses unless you allow them. That default protects your network from your visitors; change it only on a machine where every user is you.
STomp is licensed under the GPL-3.0. Found a mistake in these pages? Open an issue.