Skip to content

About

Production-focused WebTransport for Bun, powered by a Rust napi-rs addon (wtransport). In-process server and client, datagrams + uni/bidi streams, Chromium interop, bounded queues/backpressure defaults, and runnable examples (local, Docker, and Compose) for real-time systems beyond WebSockets.

Resources

Contributing

Security policy

Stars

29 stars

Watchers

5 watching

Forks

Latest commit

 

History

1,788 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

webtransport-bun

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`.

npm version npm downloads CI Release CodeQL Trivy

Why Try This

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).

Who This Is For

  • 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.

Who This Is Not For

  • Teams needing full browser WebTransport spec parity.
  • Cases where plain WebSockets are fully sufficient and simpler to operate.

Use Cases

  • 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.

Feature Matrix

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

Benchmarks

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

Migration From WebSocket (Quick Guide)

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

Demo

  • 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.

Documentation

  • 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

Status

  • npm latest is 0.3.0, an older pre-1.0 API that exports only the root (native) entrypoint: a plain bun add @webtransport-bun/webtransport installs it, and /wasm, /portable and /sink-reader do not exist there.
  • The 1.0 surface this README documents is published only under the canary and nightly dist-tags (bun add @webtransport-bun/webtransport@canary). No 1.0 release candidate is on npm: the v1.0.0-rc.N releases (up to v1.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 in docs/release-status.json; the native root entrypoint and /wasm are candidate surfaces, not stable/GA.
  • Configured release targets: Bun (>= 1.3.14), Node, and Deno. Candidate support remains unclaimed until the matching entries in docs/release-status.json have 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.json until the external evidence gates close.
  • Known runtime hazard: Bun <= 1.3.13 permanently leaks one WritableStream (plus its rejection Error) 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=1 silences it). Use Bun >= 1.3.14.

Configured Target Matrix

Runtime

  • 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

OS / Arch

  • 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.

Install

From package

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, /portable and /sink-reader
  • prebuilds/ native addon binaries (.node) for the configured target matrix
  • wasm-dist/ the prebuilt wasm engine used by /wasm
  • README.md and LICENSE

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.

From local workspace (development)

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/webtransport

bun 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.

Examples

  • 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:echo

Then 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:docker

Run multi-node compose collaboration example:

bun run example:compose:collab

WASM Backend: WebTransport Server in the Browser

Beyond 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 Sockets UDPSocket in a Chromium Isolated Web App (DirectSocketsUdpTransport), Bun.udpSocket in 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 the serverCertificateHashes value; connectWasm(...) / createUnifiedClient(...) connect as a client.
  • Backend-agnostic contract: WebTransportLike (exported from both the root and /wasm subpaths) lets application code run unchanged against the native or wasm backend. On native, get one with nativeToWebTransportLike(new WebTransport(url, opts)), or from an existing connect() session with nativeToWebTransportLike(toWebTransport(session)).
  • One server, either backend: @webtransport-bun/webtransport/portable exports an async createServer that dispatches on the runtime, handing your onSession the same session shape on both. See below.
  • Certs: generateCert produces browser-pinnable ECDSA P-256 certs (validity clamped to the 14-day serverCertificateHashes limit).
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 down

The 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();

Know before you ship

  • /wasm is a candidate surface, not stable/GA — but its export list is frozen. Those are two different promises. The names exported from /wasm are pinned by packages/webtransport/test/public-surface-contract.test.ts, so removing or renaming one is a breaking change needing a major bump. What is still candidate is the stability label: docs/release-status.json marks both native and wasm as candidate, and /wasm becomes stable only once its required claims pass. Behavior under those gates may still change. The wasm server session mirrors the native ServerSession shape — incomingDatagrams(), the incoming stream ReadableStreams, and id/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 UDPSocket does not exist on normal web pages, in Firefox, or in Safari. Installing an IWA today requires chrome://flags (#enable-isolated-web-apps, #enable-isolated-web-app-dev-mode) or enterprise policy. Chromium permission naming is compatibility-sensitive: accept direct-sockets, the legacy direct-sockets-private, and Chrome 151 local-network / loopback-network labels 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. serverCertificateHashes pinning (the only option without a CA-trusted cert) requires ECDSA P-256 and a validity window of at most two weeks — generateCert clamps 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 wrap Bun.udpSocket yourself, as in the snippet above. Inside a Chromium IWA with Direct Sockets, await createServer(...) from @webtransport-bun/webtransport/wasm (alias createIwaServer) owns bind + pumps for you. That is not the root package's native sync createServer, 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).

Quickstart

1) Install package

bun add @webtransport-bun/webtransport@canary   # 1.0 surface; plain `latest` is 0.3.0

2) Start a server

import { 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);

3) Connect a client

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();

4) Connect a client (W3C-like facade)

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: when true, endpoint-level pooling reuses compatible connects; when false, 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 with allowPooling: true.
  • datagramsReadableType: "bytes" uses ReadableByteStream with BYOB; "default" uses normal ReadableStream.
  • congestionControl: accepted and surfaced via effective-mode behavior.

From Source (Local Development)

When running directly from this monorepo (imports from packages/webtransport/src resolve the addon in crates/native/):

bun install
bun run build:native

To consume the checkout from another project, see "From local workspace" above.

Stream Controls

The stream helpers are symbol-based to avoid collisions with Node stream APIs:

  • WT_RESET
  • WT_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);

Default Limits

Important defaults (configurable via limits):

  • maxSessions: 2000
  • maxStreamsGlobal: 50000
  • maxDatagramSize: 1200
  • maxQueuedBytesGlobal: 512 MiB
  • backpressureTimeoutMs: 5000
  • handshakeTimeoutMs: 10000
  • idleTimeoutMs: 60000

Incoming Datagram Delivery

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 max already-received datagrams after the session is closed, instead of at most one.
  • Abandoning the iterator mid-batch discards up to max - 1 already-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=0 lane 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.

Verification Commands

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

Operational Caveats

  • WebTransport requires UDP reachability for your configured port.
  • Use valid TLS certs for browser/public deployments.
  • insecureSkipVerify is for development only.
  • If memory pressure rises, lower queue/session limits first, then scale out.

See docs/OPERATIONS.md for runbooks.

Release Checklist

  • 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

Used By

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

License

MIT. See LICENSE.

Contributing

See CONTRIBUTING.md.

About

Production-focused WebTransport for Bun, powered by a Rust napi-rs addon (wtransport). In-process server and client, datagrams + uni/bidi streams, Chromium interop, bounded queues/backpressure defaults, and runnable examples (local, Docker, and Compose) for real-time systems beyond WebSockets.

Resources

Contributing

Security policy

Stars

29 stars

Watchers

5 watching

Forks

Releases

Packages

Used by

Contributors

Languages