WebTransport for Bun, Node, and Deno with production guardrails: datagrams + streams, in-process server/client, and Chromium interop backed by Rust `wtransport` via `napi-rs`.
webtransport-bun is for teams that need realtime transport beyond WebSockets without giving up JS runtime ergonomics.
- Mix unreliable low-latency traffic and reliable ordered traffic in one session.
- Run WebTransport server and client in-process in Bun, Node, or Deno.
- Keep ops predictable with queue/memory/rate limits and backpressure timeouts.
- Use browser clients (Chromium interop tested in CI).
- Teams building collaboration/presence workloads with high update rates.
- Multiplayer or telemetry-heavy backends where packet loss tolerance matters.
- Services moving from WebSockets to QUIC/WebTransport while staying in JS runtimes.
- Systems needing streams for commands/state sync and datagrams for fast signals.
- Teams needing full browser WebTransport spec parity.
- Cases where plain WebSockets are fully sufficient and simpler to operate.
- Collaboration and presence: cursors/typing over datagrams, edits/events over streams.
- Multiplayer and game telemetry: frequent state deltas + reliable control channels.
- IoT / high-frequency ingest: lossy telemetry + reliable config/ack flows.
- Realtime AI/control channels: low-latency control messages + reliable command streams.
| Capability | webtransport-bun |
WebSocket stacks | Raw QUIC libs (wtransport/quinn) |
|---|---|---|---|
| In-process server (Bun/Node/Deno) | Yes | Yes | No (requires custom bindings/service) |
| In-process client (Bun/Node/Deno) | Yes | Yes | No (requires custom bindings/service) |
| Datagram + stream model | Yes | No (single reliable channel) | Yes |
| Browser WebTransport interop | Yes (Chromium-tested) | No | Indirect/custom |
| Operational defaults (limits, abuse controls) | Yes | Varies by app | You build it |
| JS-first API surface | Yes | Yes | No |
Benchmark baselines and methodology:
docs/BENCHMARK_BASELINES.md
Reproducible commands:
bun run bench:datagram
bun run bench:handshake
bun run bench:stream
bun run bench:baseline| Existing WebSocket pattern | WebTransport channel in webtransport-bun |
|---|---|
| Presence pings / cursors / telemetry | Datagrams |
| Chat / reliable app events | Bidirectional stream |
| Server snapshots / state dumps | Unidirectional stream from server |
| Single-message envelope for all traffic | Split by semantics: datagram vs stream |
Detailed migration playbook:
docs/MIGRATION_WEBSOCKET.md
- Local interactive demo:
examples/echo-playground - Multi-node compose demo:
examples/compose-collab - Recommended short walkthrough to record/share: run compose demo + open
http://localhost:8080/dashboard.
- Docs portal:
docs/START_HERE.md - Canonical release truth:
docs/release-status.json - Pooling semantics (
allowPooling):docs/SPEC.md— Pooling Semantics section - GitHub Pages docs site:
https://vmeansdev.github.io/webtransport-bun/ - FAQ / troubleshooting:
docs/FAQ.md - Migration guide:
docs/MIGRATION_WEBSOCKET.md - AI-agent entrypoint:
llms.txt
- npm
latestis0.3.0, an older pre-1.0 API that exports only the root (native) entrypoint: a plainbun add @webtransport-bun/webtransportinstalls it, and/wasm,/portableand/sink-readerdo not exist there. - The 1.0 surface this README documents is published only under the
canaryandnightlydist-tags (bun add @webtransport-bun/webtransport@canary). No 1.0 release candidate is on npm: thev1.0.0-rc.Nreleases (up tov1.0.0-rc.5) exist only as git tags and GitHub pre-releases. No 1.0 release date is set. - The committed package version is the base
1.0.0; the release and channel workflows stamp the published version. The canonical release status lives indocs/release-status.json; the native root entrypoint and/wasmare candidate surfaces, not stable/GA. - Configured release targets: Bun (
>= 1.3.14), Node, and Deno. Candidate support remains unclaimed until the matching entries indocs/release-status.jsonhave passing evidence. - Server and client APIs are available from
@webtransport-bun/webtransport. - Known limits: Chromium-focused browser interop target. Readiness remains pending in
docs/release-status.jsonuntil the external evidence gates close. - Known runtime hazard: Bun
<= 1.3.13permanently leaks oneWritableStream(plus its rejectionError) for every stream whose close is rejected — e.g. any peer that drops its receive half. Long-running servers on those runtimes exhaust memory; the library warns once at startup (WEBTRANSPORT_SUPPRESS_RUNTIME_VERSION_WARN=1silences it). Use Bun>= 1.3.14.
- Bun
>= 1.3.14 - Node
>= 18(engines.node); CI runs the package-consumer smoke on Node 18.20.4, 20.19.0 and 22.23.1 - Deno (npm + Node-API addon support); CI runs the same smoke on Deno 2.9.3
- macOS arm64 (
darwin-arm64), macOS x64 (darwin-x64) - Linux x64, glibc (
linux-x64-gnu) - Windows x64 (
win32-x64-msvc)
See docs/COMPATIBILITY.md for policy details.
bun add @webtransport-bun/webtransport@canary
npm i @webtransport-bun/webtransport@canary
pnpm add @webtransport-bun/webtransport@canary
yarn add @webtransport-bun/webtransport@canary@canary (and @nightly) carry the 1.0 surface this README documents. Without
a tag you get npm latest, which is 0.3.0: an older API with the root
entrypoint only (see Status).
The 1.0 npm package contains:
dist/compiled JS + TypeScript declarations for the four entrypoints:@webtransport-bun/webtransport(native),/wasm,/portableand/sink-readerprebuilds/native addon binaries (.node) for the configured target matrixwasm-dist/the prebuilt wasm engine used by/wasmREADME.mdandLICENSE
Note: GitHub source zip/tar downloads are source snapshots and may not include generated dist/. Use npm install (or the release .tgz package asset) for a ready-to-run package.
The package's entrypoints point at compiled dist/, the addon is looked up in
prebuilds/ next to it, and /wasm loads the engine from wasm-dist/, so
build all three before installing from a checkout (the wasm step needs the
Rust and wasm-bindgen toolchain described in crates/wasm/build-wasm.sh;
skip it if you only use the native root entrypoint):
bun install
bun run build:native # addon -> crates/native/*.node
bun run build:wasm:dist # wasm engine -> packages/webtransport/wasm-dist
bun run --cwd packages/webtransport build # TypeScript -> packages/webtransport/dist
mkdir -p packages/webtransport/prebuilds
cp crates/native/webtransport-native.*.node packages/webtransport/prebuilds/Then, from your project:
bun add file:/path/to/webtransport-bun/packages/webtransportbun add file: copies the package into your node_modules instead of
linking it: after rebuilding the checkout, run bun install in your project
again to refresh the copy with the new dist/, prebuilds/ and wasm-dist/.
Set WEBTRANSPORT_NATIVE_ADDON_PATH=/path/to/webtransport-native.<platform>.node
to load an addon from anywhere else.
- Browser + runtime echo playground (datagrams, bidi, uni):
examples/echo-playground - Compose collaboration room (1 server + 3 clients):
examples/compose-collab
Quick run:
bun run build:native
bun run example:echo:cert
bun run example:echoThen open http://127.0.0.1:3000.
Dockerized example is available at examples/echo-playground/Dockerfile.
Run Docker example in one command:
bun run example:echo:dockerRun multi-node compose collaboration example:
bun run example:compose:collabBeyond the native napi-rs addon, the package ships a sans-IO wasm backend
(@webtransport-bun/webtransport/wasm) that runs the full
QUIC/TLS1.3/HTTP3/WebTransport stack compiled to wasm32-unknown-unknown —
including a server running inside the browser (issue #12: bring your own
UDP socket).
The current release status is pending in docs/release-status.json; treat the
/wasm surface as a candidate, not stable/GA.
- Bring your own socket: the core never touches the network. Any transport
implementing
UdpTransport(send(data, dest)+onPacket(data, source)) feeds it raw UDP payloads — Direct SocketsUDPSocketin a Chromium Isolated Web App (DirectSocketsUdpTransport),Bun.udpSocketin Bun (a few lines of your own, below), or an in-memory relay in tests (InMemoryRelay). - Server + client:
serveOverUdp(...)accepts sessions (multi-client, routed per source address) and returns theserverCertificateHashesvalue;connectWasm(...)/createUnifiedClient(...)connect as a client. - Backend-agnostic contract:
WebTransportLike(exported from both the root and/wasmsubpaths) lets application code run unchanged against the native or wasm backend. On native, get one withnativeToWebTransportLike(new WebTransport(url, opts)), or from an existingconnect()session withnativeToWebTransportLike(toWebTransport(session)). - One server, either backend:
@webtransport-bun/webtransport/portableexports an asynccreateServerthat dispatches on the runtime, handing youronSessionthe same session shape on both. See below. - Certs:
generateCertproduces browser-pinnable ECDSA P-256 certs (validity clamped to the 14-dayserverCertificateHasheslimit).
import {
loadWasmModule,
serveOverUdp,
toWasmServerSession,
type UdpTransport,
} from "@webtransport-bun/webtransport/wasm";
// The package ships no Bun UDP adapter; this is the whole of one. Inside a
// Chromium IWA, pass DirectSocketsUdpTransport.bind instead.
async function bindUdp(localAddress: string, localPort: number): Promise<UdpTransport> {
let onPacket: ((data: Uint8Array, src: { address: string; port: number }) => void) | undefined;
const socket = await Bun.udpSocket({
hostname: localAddress,
port: localPort,
socket: { data: (_s, buf, port, address) => onPacket?.(new Uint8Array(buf), { address, port }) },
});
return {
localPort: socket.port,
send: (data, dest) => void socket.send(data, dest.port, dest.address),
onPacket: (fn) => { onPacket = fn; },
close: () => socket.close(),
};
}
const wasm = await loadWasmModule(); // prebuilt artifact shipped in the package
const { manager, certHashBase64 } = await serveOverUdp(wasm, bindUdp, {
localPort: 4433,
onSession: async (raw) => {
const session = toWasmServerSession(raw);
for await (const d of session.incomingDatagrams()) {
await session.sendDatagram(d);
}
},
});
// clients pin certHashBase64; manager.close() shuts the server downThe same echo server, written once and run on whichever backend the runtime provides:
import { createServer } from "@webtransport-bun/webtransport/portable";
const server = await createServer({
port: 4433,
// A PEM pair works on both backends. On wasm only, `{ allowSelfSigned: true }`
// generates a short-lived browser-pinnable cert instead; native rejects it.
tls: {
certPem: await Bun.file("cert.pem").text(),
keyPem: await Bun.file("key.pem").text(),
},
onSession: async (session) => {
for await (const d of session.incomingDatagrams()) {
await session.sendDatagram(d);
}
},
});
// wasm clients pin server.certHashBase64
await server.close();/wasmis a candidate surface, not stable/GA — but its export list is frozen. Those are two different promises. The names exported from/wasmare pinned bypackages/webtransport/test/public-surface-contract.test.ts, so removing or renaming one is a breaking change needing a major bump. What is stillcandidateis the stability label:docs/release-status.jsonmarks bothnativeandwasmascandidate, and/wasmbecomesstableonly once its required claims pass. Behavior under those gates may still change. The wasm server session mirrors the nativeServerSessionshape —incomingDatagrams(), the incoming streamReadableStreams, andid/peer— so one server codebase runs on either backend through@webtransport-bun/webtransport/portable, which is the subset actually contract-tested on both. What remains divergent is the original callback-style API (onDatagram/onIncomingStream), kept for back-compat but deprecated; it cannot be combined with the W3C surface on the same session.- The in-browser server is Chromium-only, and only inside an Isolated Web
App. Direct Sockets
UDPSocketdoes not exist on normal web pages, in Firefox, or in Safari. Installing an IWA today requireschrome://flags(#enable-isolated-web-apps,#enable-isolated-web-app-dev-mode) or enterprise policy. Chromium permission naming is compatibility-sensitive: acceptdirect-sockets, the legacydirect-sockets-private, and Chrome 151local-network/loopback-networklabels where the browser exposes them. Connecting to a wasm server needs no flags - any standard WebTransport client works. - Certificates expire in ≤ 14 days by design.
serverCertificateHashespinning (the only option without a CA-trusted cert) requires ECDSA P-256 and a validity window of at most two weeks —generateCertclamps to this. Plan for rotation: regenerate and redistribute the hash before expiry; clients pin the hash, so a new cert means a new hash. - You bring the I/O — unless you use IWA plug-and-play. The wasm core is
sans-IO: it never opens sockets, reads clocks, or schedules timers by itself.
The shipped adapters (
DirectSocketsUdpTransport,InMemoryRelay) pump packets and drive timeouts; under Bun you wrapBun.udpSocketyourself, as in the snippet above. Inside a Chromium IWA with Direct Sockets,await createServer(...)from@webtransport-bun/webtransport/wasm(aliascreateIwaServer) owns bind + pumps for you. That is not the root package's native synccreateServer, and it still cannot run on a normal webpage. - Client-side wasm works anywhere wasm runs (Bun, Node, browsers) against any WebTransport server — the IWA constraint applies only to hosting a server in the browser.
Typical use cases: browser-to-browser P2P on a LAN without WebRTC signaling, kiosk/enterprise IWAs accepting connections from local devices, offline or air-gapped networks, and in-page loopback for protocol testing against Chromium's own native client.
See examples/webtransport-wasm-iwa/ for the in-browser (IWA) reference,
tools/interop/WASM_INTEROP.md for the cross-stack interop matrix, and
docs/PARITY_MATRIX.md for native-vs-wasm feature parity (pooling, stats, CC,
sendOrder, durable tickets, live TLS, metrics — IWA async createServer on
/wasm is available as a candidate; lower-level hosts may still supply
UdpTransport).
bun add @webtransport-bun/webtransport@canary # 1.0 surface; plain `latest` is 0.3.0import { createServer } from "@webtransport-bun/webtransport";
import { readFileSync } from "node:fs";
// Dev cert: see docs/GETTING_STARTED.md ("Minimal server example") for a
// one-line openssl command that writes cert.pem / key.pem.
const certPem = readFileSync("./cert.pem", "utf-8");
const keyPem = readFileSync("./key.pem", "utf-8");
const server = createServer({
host: "0.0.0.0",
port: 4433,
tls: { certPem, keyPem },
onSession: async (session) => {
for await (const d of session.incomingDatagrams()) {
await session.sendDatagram(d);
}
},
});
console.log("listening:", server.address);import { connect } from "@webtransport-bun/webtransport";
const session = await connect("https://127.0.0.1:4433", {
tls: { insecureSkipVerify: true }, // dev only
});
await session.sendDatagram(new Uint8Array([1, 2, 3]));
for await (const d of session.incomingDatagrams()) {
console.log("echo:", d);
break;
}
session.close();import { WebTransport } from "@webtransport-bun/webtransport";
const wt = new WebTransport("https://127.0.0.1:4433", {
tls: { insecureSkipVerify: true }, // dev only
});
await wt.ready;
const writer = wt.datagrams.writable.getWriter();
await writer.write(new Uint8Array([1, 2, 3]));
writer.releaseLock();
const reader = wt.datagrams.readable.getReader();
const { value } = await reader.read();
console.log("echo:", value);
reader.releaseLock();
wt.close({ closeCode: 1000, reason: "done" });
await wt.closed;W3C-facade option semantics in this runtime:
allowPooling: whentrue, endpoint-level pooling reuses compatible connects; whenfalse, dedicated sessions.requireUnreliable: accepted; satisfied by QUIC/WebTransport transport capabilities.serverCertificateHashes: supported (SHA-256 leaf pinning, W3C semantics — the pin replaces CA/hostname validation so self-signed pinned certs are accepted, with a ≤14-day cert-validity guard) and rejected when combined withallowPooling: true.datagramsReadableType:"bytes"usesReadableByteStreamwith BYOB;"default"uses normalReadableStream.congestionControl: accepted and surfaced via effective-mode behavior.
When running directly from this monorepo (imports from
packages/webtransport/src resolve the addon in crates/native/):
bun install
bun run build:nativeTo consume the checkout from another project, see "From local workspace" above.
The stream helpers are symbol-based to avoid collisions with Node stream APIs:
WT_RESETWT_STOP_SENDING
import type { Duplex } from "node:stream";
import {
WT_RESET,
type Resettable,
type StopSendable,
} from "@webtransport-bun/webtransport";
// The session API types streams as plain Node Duplexes; the symbol methods
// are on the runtime object, so cast to reach them.
const bidi = (await session.createBidirectionalStream()) as Duplex &
Resettable &
StopSendable;
bidi[WT_RESET](42);Important defaults (configurable via limits):
maxSessions:2000maxStreamsGlobal:50000maxDatagramSize:1200maxQueuedBytesGlobal:512 MiBbackpressureTimeoutMs:5000handshakeTimeoutMs:10000idleTimeoutMs:60000
incomingDatagrams() is unchanged as an API: an AsyncIterable<Uint8Array>,
memoized per session, one datagram per yield, in receive order, terminating on
close. Under it, the native backend reads datagrams from the addon in batches
instead of one Node-API call per datagram.
WEBTRANSPORT_DATAGRAM_BATCH sets the batch size. It is read once at module
load and is native-only — the wasm backend does not use Node-API and is
unaffected, including when a wasm session is reached through /portable.
| Value | Effect |
|---|---|
| unset or invalid (empty, non-decimal, non-finite, non-integer) | 64 (default) |
0 |
legacy one-call-per-datagram path (rollback lane) |
1 |
new path with one-item batches |
2–256 |
batch size |
| negative | 0 |
above 256 |
256 |
Three delivery behaviors change with batching, all of them permitted for an unreliable transport but worth knowing:
- The iterator may yield up to
maxalready-received datagrams after the session is closed, instead of at most one. - Abandoning the iterator mid-batch discards up to
max - 1already-received datagrams, instead of at most one. - Close-time drop-not-drain: on close, a parked or newly entered read returns
end-of-stream immediately and datagrams still queued in native are discarded
rather than drained (previously they were drained first). This one applies on
both the server and client handles, and to the legacy
WEBTRANSPORT_DATAGRAM_BATCH=0lane too, since they all share the same close wake. Internal budgets and gauges still settle; the drop is about what reaches JavaScript.
Effective receive buffering per session becomes 2048 + max datagrams on the
server and 256 + max on the client, and the per-session byte budget is
loosened by up to one batch of payload bytes. No new batch is requested until
the consumer has drained the previous one, so total in-flight data stays
bounded.
The knob is a performance dial, but it is not only that: on a clean peer close
the amount of tail a consumer receives depends on the batch size and is not
guaranteed. Batching wins that race more often because it needs one
round-trip instead of one per datagram — in one measured run, 2 of 12 tail
datagrams at 0 versus 12 of 12 at 64. Those counts illustrate the effect;
being the outcome of a race, they are not a figure to hold the library to.
Treat a tail length change after
retuning the knob as expected, not as a bug.
Full contract: docs/SPEC.md → "Incoming datagram delivery"; per-backend
bounds: docs/PARITY_MATRIX.md.
From repository root:
cargo fmt --check
cargo clippy --workspace -- -D clippy::all
cargo test --workspace
bun run typecheck
bun test packages/
bun run test:parity
bun run test:load-addon
bun run test:load-scale-addon
bun run test:overload-addon
bun run test:load-profiles-addon
bun run bench:handshake
SOAK_DURATION=120 bun run test:soak-addon
bun run test:interop
bun tools/smoke-readme.ts- WebTransport requires UDP reachability for your configured port.
- Use valid TLS certs for browser/public deployments.
insecureSkipVerifyis for development only.- If memory pressure rises, lower queue/session limits first, then scale out.
See docs/OPERATIONS.md for runbooks.
- API and behavior review:
docs/SPEC.md - Test gates:
docs/TESTPLAN.md - CI and release flow:
docs/CI.md - Operations runbooks:
docs/OPERATIONS.md - Compatibility policy:
docs/COMPATIBILITY.md
Using this in production? Let me know and I will list your company/project.
- Adopters list:
ADOPTERS.md - Add yourself via issue:
.github/ISSUE_TEMPLATE/add-adopter.md
MIT. See LICENSE.
See CONTRIBUTING.md.