# Cap'n Web > A JavaScript-native, object-capability RPC system with promise pipelining. No schemas, no boilerplate, under 17 kB. Index: https://capnweb.com/llms.txt # Cap'n Web > A JavaScript-native, object-capability RPC system with promise pipelining. No schemas, no boilerplate, under 17 kB. Source: https://capnweb.com/ · Markdown: https://capnweb.com/index.md import { examples } from '../../examples.ts'; import bundleSize from '../../generated/bundle-size.json'; import CanvasFigure from '../../components/canvas-hero/CanvasFigure.astro'; import Features from '../../components/Features.astro'; import NavList from '../../components/NavList.astro'; import { HERO_TITLE, HERO_FIGURE_CAPTION, heroTagline } from '../../lib/hero-copy.ts'; Cap'n Web is a spiritual sibling to [Cap'n Proto](https://capnproto.org), created by the same author, but designed to play nice in the web stack. Like Cap'n Proto it is an **object-capability** protocol: "Cap'n" is short for "capabilities and". Unlike Cap'n Proto, it has no schemas, almost no boilerplate, and its serialization is just JSON with a little pre- and post-processing. ## Why it's different ## The magic trick Every call returns an `RpcPromise`. You can use that promise, or a property of it, as the input to another call *before it has resolved*. The server substitutes the real value on arrival, so a chain of dependent calls costs exactly one round trip: ```ts // Authenticate, get the user's ID, fetch their profile, and // fetch every friend's profile too. One request, one response. let authed = api.authenticate(apiToken); let profile = api.getUserProfile(authed.getUserId()); let friends = authed.getFriendIds().map(id => api.getUserProfile(id)); let [me, myFriends] = await Promise.all([profile, friends]); ``` [See how promise pipelining works →](/start/pipelining-tour/) — a step-by-step tour, and the record-replay trick behind `.map()`. ## See it running Both examples run right here in the docs, with the source alongside them. They make the same point from opposite ends of the stack: the pipelined version issues one HTTP request where the ordinary version issues three. ({ title: example.title, description: example.description, href: example.docsPath, }))} /> ## Get going # Disposal > Why garbage collection can't manage remote references, and the ownership rules Cap'n Web uses instead. Source: https://capnweb.com/concepts/disposal/ · Markdown: https://capnweb.com/concepts/disposal/index.md ## Why you have to think about this Unfortunately, garbage collection does not work well when remote resources are involved, for two reasons: 1. Many JavaScript runtimes only run the garbage collector when they sense **memory pressure**. If memory is not running low, they figure there's no need to reclaim any. But a runtime has no way to know if the *other* side of an RPC connection is suffering memory pressure. 2. Garbage collectors need to **trace the full object graph** to detect which objects are unreachable, especially when those objects contain cyclic references. But a collector can only see local objects; it cannot trace through the remote graph to discover cycles that cross RPC connections. Both problems might be solvable with sufficient work, but the problem seems exceedingly difficult. This library makes no attempt to solve it. :::note We might extend Cap'n Web to use `FinalizationRegistry` to automatically dispose abandoned stubs in the future, but even if we do, it should not be relied upon, for the reasons above. ::: ## Two strategies **1. Explicitly dispose stubs when you are done with them.** This notifies the remote end that it can release the associated resources. **2. Use short-lived sessions.** When a session ends, all stubs are implicitly disposed. With [HTTP batch](/transports/http-batch/) requests there's generally no need to dispose stubs at all. With long-lived [WebSocket](/transports/websocket/) sessions, disposal may be important. ## How to dispose Stubs integrate with JavaScript's [explicit resource management](https://v8.dev/features/explicit-resource-management), which became widely available in mid-2025 (and has been supported via transpilers and polyfills for a few years before that). In short: - Disposable objects, including stubs, have a `[Symbol.dispose]` method. You can call it directly: `stub[Symbol.dispose]()`. - You can arrange for a stub to be disposed automatically at the end of a function scope by assigning it to a `using` variable, like `using stub = api.getStub();`. The disposer is invoked automatically when the variable goes out of scope. ## Automatic disposal rules This library implements several rules to make resource management more manageable. They may appear a bit complicated, but they are intended to implement the behaviour you would naturally expect. The basic principle is: **the caller is responsible for disposing all stubs.** That is: - Stubs passed in the params of a call remain property of the caller, and must be disposed by the caller, not the callee. - Stubs returned in the result of a call have their ownership transferred from the callee to the caller, and must be disposed by the caller. In practice, the callee and caller do not actually share the same stubs. When stubs are passed over RPC they are **duplicated**, and the target object is only disposed when all duplicates are disposed. So, to achieve the rule that only the caller needs to dispose, the RPC system implicitly disposes the callee's duplicates when the call completes: - Any stubs the callee receives in the parameters are implicitly disposed when the call completes. - Any stubs returned in the results are implicitly disposed some time after the call completes, specifically once the RPC system knows there will be no more pipelined calls. ### Wonky details - Disposing an `RpcPromise` automatically disposes the future result. It may also cause the promise to be cancelled and rejected, though this is not guaranteed. If you don't intend to await an RPC promise, dispose it. - Passing an `RpcPromise` in params or the return value of a call has the same ownership and disposal rules as passing an `RpcStub`. - When you access a property of an `RpcStub` or `RpcPromise`, the result is itself an `RpcPromise`, but it does not have its own disposer. You must dispose the stub or promise it came from. You can pass such properties in params or return values, but doing so never leads to anything being implicitly disposed. - The caller of an RPC may dispose stubs used in the parameters immediately after initiating the RPC, without waiting for it to complete. All stubs are duplicated at the moment of the call, so the callee is not responsible for keeping them alive. - If the final result of an RPC is an object, it will always have a disposer. Disposing it disposes all stubs found in that response. It's a good idea to always dispose return values even if you don't expect them to contain stubs, in case the API adds stubs to the result in the future. ## Duplicating stubs Sometimes you need to pass a stub somewhere it will be disposed, but also keep it for later use. To prevent the disposer from disabling your copy, duplicate it with `stub.dup()`. The stub's target is only disposed when all duplicates have been disposed. :::tip You can call `.dup()` on a *property* of a stub or promise, to create a stub backed by that property. This is particularly useful when you know in advance that the property will resolve to a stub: `.dup()` gives you a stub you can start using immediately, that otherwise behaves exactly like the eventual stub would if you awaited it. ::: ### Holding on to a callback past the call that delivered it A common bidirectional-calling pattern is for the client to pass a callback to the server, which the server then invokes later (from a timer, an event handler, or a subsequent RPC). Because the callback parameter is a stub, and stubs in params are implicitly disposed when the call returns, the server must duplicate the stub with `.dup()` if it wants to invoke the callback after the call completes: ```ts import { type RpcStub, RpcTarget } from 'capnweb'; // A callback the client passes in: a stub wrapping a function. type Listener = RpcStub<(msg: string) => void>; class Api extends RpcTarget { #listener?: Listener; // Stubs passed as params are disposed when the call returns, so `.dup()` // to keep a reference that outlives registerListener(). registerListener(listener: Listener) { this.#listener?.[Symbol.dispose](); // release any previous listener this.#listener = listener.dup(); } // A *later* call can invoke the retained callback -- still valid thanks to .dup(). notify(msg: string) { this.#listener?.(msg); } // Dispose our duplicate when done so the client-side stub can be freed. [Symbol.dispose]() { this.#listener?.[Symbol.dispose](); } } ``` The same rule applies in the other direction: if the server returns a stub to the client and the client wants to keep using it after disposing the result, the client should `.dup()` the stub before the result is disposed. ## Listening for disposal An `RpcTarget` may declare a `Symbol.dispose` method. If it does, the RPC system automatically invokes it when a stub pointing at it, and all its duplicates, have been disposed. If you pass the same `RpcTarget` instance to RPC multiple times (creating multiple stubs), you will eventually get a separate dispose call for each one. To avoid this, use `new RpcStub(target)` to create a single stub upfront, then pass that stub across multiple RPCs. You will then receive only one call to the target's disposer, when all stubs are disposed. ## Listening for disconnect Monitor any stub for "brokenness" with `onRpcBroken()`: ```ts stub.onRpcBroken((error: any) => { console.error(error); }); ``` If anything happens to the stub that would cause all further method calls and property accesses to throw exceptions, the callback is called. In particular, this happens if: - The stub's underlying connection is lost. - The stub is a promise, and the promise rejects. # The magic map() > Transform a remote value in place with .map(), the rules it imposes, and the record-replay mechanism that makes it possible. Source: https://capnweb.com/concepts/map/ · Markdown: https://capnweb.com/concepts/map/index.md Every RPC promise has a special method `.map()` which can be used to remotely transform a value, without pulling it back locally. ```ts // Get a list of user IDs. let idsPromise = api.listUserIds(); // Look up the username for each one. let names = await idsPromise.map(id => [id, api.getUserName(id)]); ``` This calls one API method to get a list of user IDs, then, for each user ID in the list, makes another RPC call to look up the user's name, producing a list of id/name pairs. **All this happens in a single network round trip.** ## Semantics `promise.map(func)` transfers a representation of `func` to the peer, where it is executed on the promise's result. Specifically: - If the promise resolves to an **array**, the mapper executes on each element. The overall `.map()` returns a promise for an array of the results. - If the promise resolves to **`null` or `undefined`**, the mapper is not executed at all. The result is the same value. - If the promise resolves to **any other value**, the mapper executes once on that value, returning the result. So `map()` handles both arrays and nullable values; it doubles as an "optional chaining" operator across the network. ## Restrictions :::caution - The callback must have **no side effects** other than calling RPCs. - The callback must be **synchronous**. It cannot await anything. - The input to the callback is an `RpcPromise`, so the callback cannot actually operate on it, other than to invoke its RPC methods, or use it in the params of other RPC methods. - Any stubs you use in the callback (and any parameters you pass to them) **will be sent to the peer**. A malicious peer can use these stubs for anything, not just calling your callback. Typically it only makes sense to invoke stubs that came from the same peer originally, since that is what saves the round trip. ::: Because the callback's input is an opaque promise, you cannot branch on it: ```ts // ❌ Doesn't do what you want: `id` is an RpcPromise, always truthy. ids.map(id => (id > 100 ? api.getBigUser(id) : api.getUser(id))); // ✅ Do the branching on the server side instead. ids.map(id => api.getUser(id)); ``` :::danger[TypeScript catches only some of these mistakes] The callback parameter is typed as a placeholder rather than a value, so TypeScript rejects the more obvious abuses, but not all of them, and the ones it misses are the quiet ones: | You wrote | What actually happens | TypeScript | | ------------------ | --------------------------------------- | ---------- | | `if (id)` | Always true (every object is truthy) | Compiles | | `` `user-${id}` `` | The string `"user-[object RpcPromise]"` | Compiles | | `id > 100` | Always false | Error | | `[...id]` | Throws: the placeholder is not iterable | Error | `id.length` is a third case: it is neither an error nor a mistake, because property access on a placeholder is a legitimate pipelined operation. It just gives you a promise for the length, not a number you can branch on. Use TypeScript for `.map()`, but don't assume it caught everything. ::: Two mistakes are caught at runtime rather than silently: ```ts // ❌ Throws: "RPC map() callbacks cannot be async." ids.map(async id => await api.getUser(id)); // ❌ Throws: can't construct an RpcTarget or RPC callback inside a mapper. ids.map(id => api.subscribe(id, new MyListener())); // ✅ Create the stub outside, then use it inside. using listener = new RpcStub(new MyListener()); ids.map(id => api.subscribe(id, listener.dup())); ``` The `.dup()` in that last line is required. Stubs captured by a recording are consumed when the map completes, so passing `listener` bare leaves your outer stub disposed, and the next thing you do with it throws `Attempted to use an RPC StubHook after it was disposed.` ## Which side runs what The answer has two halves: - **Your JavaScript runs on the calling side, exactly once**, when the recording is made. - **The RPC calls it recorded run on the receiving side, once per element.** So local computation is not repeated per element; it is evaluated once and the result is baked into the recording: ```ts let n = 0; ids.map(id => api.log(id, n++, new Date().toISOString())); ``` Every element receives `n === 0` and the *same* timestamp, taken from the **caller's** clock. `n` ends up as `1`, not `ids.length`. Anything locale- or environment-dependent, such as `toLocaleString()`, `Math.random()`, or `Date.now()`, samples the calling side once. That is usually not what you want inside a map, so compute it on the peer instead by calling a method. RPC calls, including calls on stubs you captured from outside the callback, *do* run once per element: ```ts let counter = new RpcStub(new Counter(0)); // counter.increment() is called once per element, not once total. await ids.map(id => { counter.increment(); return api.getUser(id); }); ``` There is also no index argument. `.map()` passes one parameter, and TypeScript will reject a callback that declares two. An index would have to be a promise for the index, which you could not do arithmetic on anyway. If you need positions, have the peer return them. ## Why only `.map()`? `.map()` is the only array combinator Cap'n Web special-cases, and that is a deliberate stopping point rather than a to-do item. `.map()` works precisely because the common case *does no computation on the values*: it just pipelines each element into another RPC, which is exactly what a recording can express. `filter()`, `find()`, `reduce()` and `sort()` all require actually evaluating something about each value, and the callback never sees values. Making those work would mean shipping an expression library in the protocol: `eq`, `gt`, `and`, `not`, arithmetic, and then everything anyone ever wants next. That library would only ever grow, it would bloat every implementation, and every operator is new surface for a peer to abuse. The supported answer is to expose the operation as an ordinary RPC method, which you can then call from inside a map callback: ```ts // On the server. class Api extends RpcTarget { // Filtering as an explicit method that takes the whole array. getActiveUsers(ids: number[]): User[] { return ids.map(lookup).filter(u => u.active); } } // On the client, still one round trip. using active = await api.getActiveUsers(api.listUserIds()); ``` This is better than a generic filter anyway: the server does the work in one query instead of answering a predicate N times, and you get to name the operation. ## How the heck does that work? Cap'n Web does **NOT** send arbitrary code over the wire. The trick is **record-replay**. On the calling side, Cap'n Web invokes your callback once, in a special "recording" mode, passing in a placeholder stub that records what you do with it. During that invocation: - Any RPCs invoked by the callback (on *any* stub) are not actually executed, but recorded as an action the callback performs. - Any stubs you use during the recording are "captured" as well. Once the callback returns, the recording and the capture list are sent to the peer, where the recording can be replayed as needed to process individual results. Since all of the not-yet-determined values seen by the callback are represented as `RpcPromise`s, the callback's behaviour is deterministic. Any actual computation (arithmetic, branching, etc.) can't possibly use these promises as meaningful inputs, so it would logically produce the same result for every invocation. Any such computation ends up being performed on the sending side, just once, with the results baked into the recording. The wire format for this is the `["remap", ...]` expression. See the [protocol reference](/reference/protocol/#remap). Because the recording is data rather than code, no arbitrary code ever crosses the wire, and a non-JavaScript peer could evaluate one; see [How it compares](/guides/comparisons/#is-it-a-protocol-or-a-javascript-library). ## Nesting and recursion `.map()` callbacks may contain further `.map()` calls, and this works exactly as you would hope: ```ts await api.listTeams().map(team => team.memberIds.map(id => api.getUserName(id))); ``` :::caution Nesting **multiplies** server-side work. A map over N elements whose callback maps over M produces N × M calls from a single client message, which is the cheapest denial-of-service in the library. [Rate-limit expensive operations](/guides/security/#rate-limit-because-pipelining-is-cheap-for-attackers). Unbounded *recursion* is comparatively harmless: recording happens on the calling side, so an infinitely recursive callback overflows the caller's own stack before anything is sent. That protects you from your own bug, not from a peer who crafts a large recording deliberately. Server-side resource limits remain your responsibility. ::: # RpcPromise & Pipelining > Why RPC calls return RpcPromise instead of Promise, and how that enables single-round-trip call chains. Source: https://capnweb.com/concepts/promises/ · Markdown: https://capnweb.com/concepts/promises/index.md Calling an RPC method returns an `RpcPromise` rather than a regular `Promise`. You can use an `RpcPromise` in all the ways a regular `Promise` can be used: you can `await` it, call `.then()`, pass it to `Promise.resolve()`, and so on. This all works because `RpcPromise` is a ["thenable"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables). But you can do more with an `RpcPromise`, because it supports **promise pipelining**. ## 1. A promise is also a stub An `RpcPromise` is a stub for the eventual result of the promise. You can access properties and invoke methods on it without awaiting it first. ```ts // In a single round trip, authenticate the user, and fetch their notifications. let user = api.authenticate(cookie); let notifications = await user.getNotifications(); ``` ## 2. A promise can be an argument An `RpcPromise`, or a property of one, can be passed as a parameter to other RPC calls. ```ts // In a single round trip, authenticate the user, and fetch their public profile // given their ID. let user = api.authenticate(cookie); let profile = await api.getUserProfile(user.id); ``` Whenever an `RpcPromise` is passed in the parameters to an RPC, or returned as part of a result, the promise is replaced with its resolution before delivery to the receiving application. So you can use an `RpcPromise` anywhere a `T` is required. ## Awaiting is what costs a round trip **Building the chain is free; awaiting is what talks to the network.** Structure your code so that everything you need is expressed before the first `await`. ```ts // ❌ Three round trips. let a = await api.first(); let b = await api.second(a); let c = await api.third(b); // ✅ One round trip. let c = await api.third(api.second(api.first())); ``` ### One round trip is not the same as one message "One round trip" is a claim about **waiting**, not about message count. | Transport | Three chained calls send… | Round trips | | ------------------------------------- | ------------------------------------------- | ----------- | | [WebSocket](/transports/websocket/) | Three `push` messages, written back-to-back | 1 | | [HTTP batch](/transports/http-batch/) | One request body containing all three | 1 | Over a WebSocket, Cap'n Web really does send a separate message per call, so if you go looking in your browser's network inspector, you will find three frames, plus a `pull` for the result you awaited and a `release` afterwards. What it does *not* do is wait for a reply in between: they all go out in the same tick and the results come back together, which in elapsed network time is indistinguishable from sending one message. The HTTP batch transport goes further and concatenates the whole batch into a single request body. **Count your `await`s, not your calls.** If you can set up an entire chain without awaiting anything, it costs one round trip no matter how many calls are in it. ## Transforming without pulling data back If you need to do something for each element of a result, use [the magic `.map()` method](/concepts/map/) rather than awaiting the array and looping: ```ts let names = await api.listUserIds().map(id => [id, api.getUserName(id)]); ``` ## Making one from a local `Promise` Normally an `RpcPromise` comes back from a call. You can also build one yourself, out of an ordinary `Promise`, with `new RpcPromise(promise)`. Pipelined calls then queue up in order and are delivered once the inner promise settles. Wrapping a promise is semantically identical to making a local-loopback RPC that returns it: ```ts import { RpcPromise, RpcStub } from 'capnweb'; let myPromise = Promise.resolve({ value: 123 }); // This... using direct = new RpcPromise(myPromise); // ...means the same as this. using rpcFunc = new RpcStub(() => myPromise); using loopback = rpcFunc(); ``` ### Call a target that does not exist yet `new RpcPromise(promise)` lets you call a target before the target exists. Here, two calls and a getter queue before the counter is created. ```ts import { RpcPromise, RpcTarget } from 'capnweb'; class Counter extends RpcTarget { #value: number; constructor(value = 0) { super(); this.#value = value; } increment(by = 1) { return this.#value += by; } get value() { return this.#value; } } { let { promise, resolve } = Promise.withResolvers(); using counter = new RpcPromise(promise); using first = counter.increment(); using second = counter.increment(10); // Property access queues the getter and returns an RpcPromise. let value = counter.value; resolve(new Counter(0)); console.log('ordered:', await first, await second, await value); } ``` This prints `ordered: 1 11 11`: pending operations run in invocation order. Property promises such as `counter.value` have no independent disposer. ### Hide connection setup behind a stub This [MessagePort](/transports/message-port/) example exposes a stub while local setup finishes. ```ts import { newMessagePortRpcSession } from 'capnweb'; class Api extends RpcTarget { authenticate(token: string) { if (token !== 's3cret') { throw new Error('bad token'); } return new Counter(100); } } { let channel = new MessageChannel(); using serverSide = newMessagePortRpcSession(channel.port1, new Api()); async function connect() { const { promise, resolve } = Promise.withResolvers(); setTimeout(resolve, 50); await promise; return newMessagePortRpcSession(channel.port2); } using api = new RpcPromise(connect()); using authed = api.authenticate('s3cret'); using result = authed.increment(5); console.log('connected:', await result); } ``` This prints `connected: 105`. The caller does not await readiness or authentication, so the calls remain pipelined. ### Reject when readiness fails A rejected source breaks the wrapper and its queued operations. ```ts { using counter = new RpcPromise( Promise.reject(new Error('connection failed')), ); counter.onRpcBroken((error: Error) => console.log('broken:', error.message)); using result = counter.increment(); try { await result; } catch (error) { if (error instanceof Error) { console.log('call:', error.message); } } } ``` The output is `broken: connection failed` followed by `call: connection failed`. Both receive the same rejection. An unused wrapper observes its backing rejection, but every queued call or `.map()` result must still be awaited or disposed. Cap'n Web processes the resolution with the same serialization, stub conversion, rejection, and ownership semantics as an RPC return: - The backing value must be a real `Promise`. - The promise may resolve to any [serializable value](/concepts/values/), an `RpcTarget` or function that Cap'n Web converts to a stub, or an `RpcStub`. - The wrapper [owns](/concepts/disposal/) every stub in the resolution. If another owner will keep using a stub, resolve with `stub.dup()`. - Rejection reaches queued operations, code awaiting the wrapper, and `onRpcBroken`. > **Pending calls have no built-in bound** > > Pending calls retain their arguments, and there is no queue limit or backpressure setting. A > readiness or reconnection producer must eventually settle. Reject on terminal failure or an > application deadline, and rate-limit untrusted callers. ## Disposal `RpcPromise` participates in [disposal](/concepts/disposal/) just like a stub: - Disposing an `RpcPromise` automatically disposes the future result. It may also cause the promise to be cancelled and rejected, though this is not guaranteed. **If you don't intend to await an RPC promise, dispose it.** - Passing an `RpcPromise` in the params or return value of a call follows the same ownership rules as passing an `RpcStub`. - When you access a property of an `RpcStub` or `RpcPromise`, the result is itself an `RpcPromise`, but this one does **not** have its own disposer. You must dispose the stub or promise it came from. ```ts { using userInfoPromise = stub.getUserInfo(); console.log(await stub.greet(userInfoPromise.name)); } // Never awaited, so the server won't even send the response back over the wire. ``` :::caution[Never disposing is a memory leak, on both sides] Un-awaited, un-disposed promises accumulate. Each one holds an entry in the session's import table, and pins the corresponding export (and the object it refers to) alive on the peer. A client that keeps issuing calls and never settles them will grow your server's memory for as long as the session lasts. This is only bounded by the session ending. The library has no reference-count limit to configure, so if you serve untrusted peers you have to bound it in application code. Attaching disposers to the values you return gives you something to count. See [Security considerations](/guides/security/) and [Sessions](/guides/sessions/). ::: ## `.dup()` on a property You can call `.dup()` on a property of a stub or promise to create a stub backed by that property. This is particularly useful when you know in advance that the property will resolve to a stub: calling `.dup()` on it gives you a stub you can start using immediately, that otherwise behaves exactly like the eventual stub would if you awaited it. # RpcTarget & Functions > Export an interface over RPC by extending RpcTarget, and understand exactly which members become reachable. Source: https://capnweb.com/concepts/rpc-target/ · Markdown: https://capnweb.com/concepts/rpc-target/index.md ## `RpcTarget` To export an interface over RPC, write a class that extends `RpcTarget`. Extending `RpcTarget` tells the RPC system: instances of this class are **pass-by-reference**. When an instance is passed over RPC, the object is NOT serialized. Instead, the message contains a stub that points back to the original target object, and invoking the stub calls back over RPC. ```ts import { RpcTarget } from 'capnweb'; class Counter extends RpcTarget { #count = 0; increment(by: number) { this.#count += by; return this.#count; } get value() { return this.#count; } } ``` ## What is reachable When you send someone an `RpcTarget` reference, they can call **any class method, including getters**. They cannot access "own" properties. In precise JavaScript terms: they can access **prototype properties but not instance properties**. This policy is intended to do the right thing for typical JavaScript code, where private members are usually stored as instance properties. **Instance properties are treated as private.** Anything assigned in the constructor, or with a class field, is an instance property and is unreachable over RPC. Reading one does not return `undefined`; it throws, so a peer cannot probe for its existence: ```text Attempted to access property 'apiKey', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. ``` That default is the safe one, and it means exposing a value is a deliberate act. ### Exposing a property with a getter A getter lives on the prototype, so it is reachable. This is the sanctioned way to publish a value that is stored privately: ```ts class Document extends RpcTarget { #title = 'Untitled'; wordCount = 0; // instance property: NOT reachable over RPC // Reachable: the peer reads `doc.title` and this getter runs. get title() { return this.#title; } // Reachable: writes have to be a method call. See below. setTitle(title: string) { this.#title = title; } } ``` :::caution A **setter can never fire over RPC**. Assigning to a stub throws `Can't assign properties on RPC stubs`, because the protocol has no message for assignment. Pairing a setter with your getter is harmless but dead code as far as a peer is concerned. Expose writes as a method instead, as `setTitle` does above. A method is also the honest shape for a write that crosses a network: it returns a promise you can await, and it can fail. ::: :::danger If you are using TypeScript, note that declaring a method `private` does **not** hide it from RPC. TypeScript annotations are erased at runtime, so they cannot be enforced. To actually make a member private, prefix its name with `#`, which makes it private to JavaScript itself. Names prefixed with `#` are never available over RPC. ::: ```ts class Api extends RpcTarget { #secret = 'not reachable'; // ✅ truly private private alsoSecret = 'reachable'; // ❌ TypeScript-only; erased at runtime #internalHelper() {} // ✅ truly private private helper() {} // ❌ callable over RPC } ``` ## Functions When a plain function is passed over RPC, it is treated similarly to an `RpcTarget`. The function is replaced by a stub which, when invoked, calls back over RPC to the original function object. ```ts // The client passes a callback... await api.subscribe((event) => console.log('got', event)); // ...and the server can invoke it, calling back into the client. ``` If the function has any own properties, those *will* be available over RPC. Note this is the opposite of `RpcTarget`: with `RpcTarget`, own properties are not exposed; with functions, *only* own properties are exposed. Generally functions don't have properties anyway. :::caution A callback stub received in a call's parameters is disposed when that call returns. If the server wants to invoke it later, it must call `.dup()`. See [holding a callback past the call](/concepts/disposal/#holding-on-to-a-callback-past-the-call-that-delivered-it). ::: ## Listening for disposal An `RpcTarget` may declare a `Symbol.dispose` method. If it does, the RPC system automatically invokes it when a stub pointing at it, and all its duplicates, has been disposed. ```ts class Session extends RpcTarget { [Symbol.dispose]() { // release resources held by this session } } ``` If you pass the same `RpcTarget` instance over RPC multiple times, creating multiple stubs, you will eventually get a separate dispose call for each one. To avoid that, use `new RpcStub(target)` to create a single stub upfront and pass that across multiple RPCs; you will then receive only one call to the target's disposer, when all stubs are disposed. # Streaming > Pass ReadableStream and WritableStream over RPC with automatic flow control and multiplexing. Source: https://capnweb.com/concepts/streaming/ · Markdown: https://capnweb.com/concepts/streaming/index.md You may pass a `ReadableStream` or `WritableStream` over RPC. When you do, the RPC system automatically creates an equivalent stream at the other end and pumps bytes (or arbitrarily typed chunks) across. ```ts class FileService extends RpcTarget { download(name: string): ReadableStream { return getFileStream(name); } async upload(name: string, data: ReadableStream) { await saveFileStream(name, data); } } ``` On the client, these look like ordinary streams: ```ts let stream = await api.download('report.csv'); for await (let chunk of stream) { // ... } ``` ## Flow control Streaming is done in such a way as to ensure the available bandwidth is fully used while minimizing buffer bloat, by observing the bandwidth-delay product and applying backpressure when too much is written. You do not configure this. Write to the stream and the RPC system throttles the writer for you. ## Multiplexing Multiple streams can be sent across the same connection; they are multiplexed appropriately, similar to HTTP/2 stream multiplexing. A large upload will not block small RPC calls happening concurrently on the same session. ## Blobs `Blob` is also supported by value. Because reading a `Blob`'s bytes is asynchronous, blobs always travel over the same pipe machinery as streams, even when small. The receiver collects all chunks before delivering the value to application code. ## Async generators are not streams `ReadableStream` is the supported way to stream. Async iteration is not an RPC concept, and the two ways of getting it wrong fail very differently: - **An async generator** is not a supported type. Returning one fails loudly, with `Cannot serialize value: [object AsyncGenerator]`. - **A plain object that merely implements `Symbol.asyncIterator`** is worse. As far as the serializer is concerned it is an ordinary object, and symbol-keyed properties are not sent, so it arrives at the peer as `{}` with no error at all. Either way, wrap it in a stream: ```ts class LogService extends RpcTarget { tail(): ReadableStream { let lines = this.#lines(); return new ReadableStream({ async pull(controller) { let { value, done } = await lines.next(); if (done) controller.close(); else controller.enqueue(value); }, cancel() { // The peer went away. Let the generator clean up. lines.return(undefined); }, }); } async *#lines() { /* ... */ } } ``` Do not skip the `cancel` handler. A consumer dropping the stream, including the peer releasing it or the session dying, is the normal way a `tail()` ends, and without `cancel` the generator is never finalized, so anything it holds open leaks. This only constrains what you *return*. The receiving side iterates a stream with `for await` just fine, as at the top of this page. ## Callbacks, when a stream is the wrong shape Streams are for a sequence of chunks flowing one way. When you want the peer to call *you* (events, progress, subscriptions), pass an object by reference instead and let it call your methods: ```ts // Client class ProgressSink extends RpcTarget { onProgress(pct: number) { updateBar(pct); } onDone() { celebrate(); } } await api.startJob(jobId, new ProgressSink()); ``` ```ts // Server class JobService extends RpcTarget { // Stubs in params are disposed when the call returns, so dup() to hold on. async startJob(jobId: string, sink: RpcStub) { using held = sink.dup(); await this.#run(jobId, held); } // `held` disposed here, releasing the client's ProgressSink } ``` This is more general than streaming, since the peer can call any method you expose in any order, but it gives you no backpressure. Awaiting every call costs a round trip per event and underuses the link; awaiting none lets the queue grow without bound. If what you actually have is a sequence of chunks, use a stream and let the flow control above do the work. Disposal doubles as a lifetime signal: your object's `[Symbol.dispose]()` runs when the peer releases it, including when the session drops, so you can detect an abandoned job. See [Disposal](/concepts/disposal/) and [Sessions](/guides/sessions/). ## How it works on the wire A `WritableStream` is exported as a `["writable", exportId]` expression whose target accepts `write(chunk)`, `close()`, and `abort(reason?)`, mirroring `WritableStreamDefaultWriter`. A `ReadableStream` is sent by first creating a pipe with a `["pipe"]` message, pumping data into the writable end immediately, and referencing the readable end via `["readable", importId]`. This means data starts flowing without waiting for a round trip. If a writable export is released without `close()` having been called, the sender aborts the stream, signalling abnormal termination such as a network disconnect. See the [protocol reference](/reference/protocol/#writable) for details. # RpcStub > How stubs work, what TypeScript knows about them, and how to forward them between peers. Source: https://capnweb.com/concepts/stubs/ · Markdown: https://capnweb.com/concepts/stubs/index.md When a type `T` which extends [`RpcTarget`](/concepts/rpc-target/) (or is a function) is sent as part of an RPC message (in the arguments to a call, or in a return value), it is replaced with a stub of type `RpcStub`. ## Stubs are proxies Stubs are implemented using JavaScript `Proxy`s. A stub appears to have every possible method and property name. The stub does **not** know at runtime which properties actually exist on the other side. If you use a property that doesn't exist, no error is produced until you await the result. TypeScript, however, knows which properties exist from the type parameter `T`. So if you are using TypeScript, you get full compile-time type checking, autocomplete, and refactoring. Hooray! ## Reading properties To read a property from the remote object, as opposed to calling a method, `await` the property: ```ts let foo = await stub.foo; ``` Property access itself is lazy and free: it produces an [`RpcPromise`](/concepts/promises/) you can also pipeline through without awaiting. ## Forwarding stubs to third parties A stub can be passed across RPC again, **including over independent connections**. If Alice is connected to Bob and Carol, and Alice receives a stub from Bob, Alice can pass that stub in an RPC to Carol, thus allowing Carol to call Bob. ```text Carol ──call──▶ Alice ──proxied──▶ Bob ``` As of this writing, any such calls are proxied through Alice. In the future we may support "three-party handoff" so that Carol can make a direct connection to Bob. In the object-capability model, possession of the stub *is* the authority to use it, and that authority is delegated by passing it along. ## Constructing a stub locally You may construct a stub explicitly, without an RPC connection: ```ts let stub = new RpcStub(target); ``` This is useful to perform local calls as if they were remote, and to manage disposal; passing one explicitly-created stub across several RPCs means the underlying target's disposer runs only once, when all copies are gone. See [Disposal](/concepts/disposal/). ## Duplicating `stub.dup()` returns an independent duplicate. The target is disposed only when *all* duplicates have been disposed. You need this whenever you want to keep a stub that the RPC system would otherwise dispose out from under you, most commonly a callback received in a call's parameters. ## Detecting breakage Monitor any stub for "brokenness" with `onRpcBroken()`: ```ts stub.onRpcBroken((error: any) => { console.error(error); }); ``` The callback fires if anything happens to the stub that would cause all further method calls and property accesses to throw. In particular: - The stub's underlying connection is lost. - The stub is a promise, and the promise rejects. # What Can Be Passed > The types Cap'n Web serializes by value, the types it passes by reference, and the types it deliberately refuses. Source: https://capnweb.com/concepts/values/ · Markdown: https://capnweb.com/concepts/values/index.md Values crossing an RPC boundary are either **passed by value** (serialized, producing a copy at the receiving end) or **passed by reference** (replaced with a stub pointing back at the original). ## Passed by value The following types can be passed over RPC, in arguments or return values: - Primitive values: strings, numbers, booleans, `null`, `undefined` - Plain objects (e.g. from object literals) - Arrays - `Set` - `bigint` - `Date` - `ArrayBuffer`, `DataView`, and typed arrays - `Error` and its well-known subclasses - `Blob` - `ReadableStream` and `WritableStream`, with automatic flow control (see [Streaming](/concepts/streaming/)) - `URL` - `RegExp` - `Headers`, `Request`, and `Response` from the Fetch API A `Set` cannot contain a promise or `Blob` directly when sent over a connection. Stubs are valid set elements, and promises and `Blob`s may still appear inside a plain object or array used as an element. ## Passed by reference - Classes that extend [`RpcTarget`](/concepts/rpc-target/) - Functions - Existing [`RpcStub`](/concepts/stubs/) and [`RpcPromise`](/concepts/promises/) values Anything passed by reference produces a **stub** on the far side, and stubs must be [disposed](/concepts/disposal/). ## Not supported yet These may be added in the future: - `Map` ## Intentionally not supported - **Application-defined classes that do not extend `RpcTarget`.** There is no safe, general way to reconstruct an arbitrary class on the other side. Convert to a plain object, or extend `RpcTarget` to pass it by reference. - **Cyclic values.** Messages are serialized strictly as trees, like JSON. ## Errors `Error` and its well-known subclasses survive the trip, including the error `message` and error subclass name. Extra own enumerable properties, `cause`, and `AggregateError`'s `errors` are carried along too; values that cannot be represented are silently dropped, but the error itself always arrives. Stack traces are **redacted by default** for security reasons, so a client cannot learn about your server's internals from a thrown error. ## On the wire All of this is JSON with a preprocessing step: non-JSON types become arrays whose first element is a type tag, like `["date", 1749342170815]`. You can read your own traffic in the browser network tab. See the [wire protocol reference](/reference/protocol/) for the full encoding. # Batch + pipelining > Three dependent RPC calls in a single HTTP round trip, running live, with the source that produces it. Source: https://capnweb.com/examples/batch-pipelining/ · Markdown: https://capnweb.com/examples/batch-pipelining/index.md import { exampleBySlug } from '../../../examples.ts'; Authenticate a user, then fetch that user's profile and notifications, both of which need the user ID that the first call returns. Pipelined, all three travel in **one** HTTP request. Written the ordinary way, they take three. Drag the latency slider and run it again. The server does identical work in both columns; the only difference is how many times the browser has to cross the network. :::note[There is no server behind this page.] The Worker on the left is bundled into the page and answers its own requests, so the round-trip counts are real but nothing crosses the network. The code and the protocol are identical either way. See [how the playground works](#how-this-page-runs). ::: ## What makes it one round trip The three calls are issued against a single session, and the second and third are built from a promise that has not resolved yet: ```js const api = newHttpBatchRpcSession(RPC_URL); const user = api.authenticate('cookie-123'); // not awaited const profile = api.getUserProfile(user.id); // uses user.id anyway const notifications = api.getNotifications(user.id); const [u, p, n] = await Promise.all([user, profile, notifications]); ``` `user.id` is not a string here. It is a *reference* to a field of a result the server has not produced yet. Cap'n Web sends that reference as part of the same batch, and the server substitutes the real value when it gets there. Nothing has to come back to the client in between. The sequential version awaits each call before building the next, so the client cannot know `user.id` until a full round trip has completed: ```js const user = await newHttpBatchRpcSession(RPC_URL).authenticate('cookie-123'); const profile = await newHttpBatchRpcSession(RPC_URL).getUserProfile(user.id); const notifications = await newHttpBatchRpcSession(RPC_URL).getNotifications(user.id); ``` Same data, same server work, three times the network cost, and that cost grows with the length of the chain, which is the part that hurts on a slow connection. ## Where the latency comes from Two separate knobs, deliberately kept apart: - **Server-side work**: per-method delays set by `DELAY_AUTH_MS`, `DELAY_PROFILE_MS` and `DELAY_NOTIFS_MS`. Identical in both modes, so it is *not* what the demo measures. - **Network round trips**: simulated in the browser by the slider. This is the part pipelining removes. Keeping the round-trip cost on the client means the deployed Worker adds no artificial delay, and the page can change it without a redeploy. ## How this page runs The demo above is the example's unmodified Worker and browser client, bundled together into one page. A small shim replaces `fetch` for the `/rpc` path and hands the request straight to the Worker's `fetch` handler: ```js globalThis.fetch = async (input, init) => { const request = new Request(input, init); if (new URL(request.url).pathname === '/rpc') { return await worker.fetch(request, ENV, ctx); } return upstream(input, init); }; ``` Everything above that line is untouched: the same session setup, the same batch encoding, the same `newWorkersRpcResponse` on the other end. Only the transport hop is gone, which is why the round-trip counts mean what they say and why these docs deploy as static files. ## Run it yourself ```sh npm run build # the examples resolve capnweb to dist/ npx wrangler dev --cwd examples/batch-pipelining --ip 127.0.0.1 --port 8788 ``` The terminal client runs the same comparison against a server in a separate process: ```sh node examples/batch-pipelining/server-node.mjs # in one shell node examples/batch-pipelining/client.mjs # in another ``` ## Next - [RpcPromise & pipelining](/concepts/promises/): how the promise references work. - [The pipelining tour](/start/pipelining-tour/): a step-by-step walkthrough, including `.map()`. - [HTTP batch transport](/transports/http-batch/): what this example is running on. # Session recovery > A WebSocket session with a button that kills it, showing what a disconnect destroys and what it takes to resume without a gap. Source: https://capnweb.com/examples/session-recovery/ · Markdown: https://capnweb.com/examples/session-recovery/index.md import { exampleBySlug } from '../../../examples.ts'; Connect, watch the events arrive, then sever the connection and reconnect. Everything comes back, including the events that happened while you were gone, because the client held on to one number. Untick **Resume from cursor** and do it again. Same disconnect, same reconnect, but now the feed shows a gap, because nothing told the server where to start. :::note[There is no server behind this page.] Both ends of the session run in this page, wired together by a shim that replaces `WebSocket` for one path. The session, the protocol, the callbacks and the disconnect are all genuine. See [how this page runs](#how-this-page-runs). ::: ## What a disconnect destroys Everything the session owned, and nothing else. | Survives | Does not survive | | ----------------------------------- | -------------------------------------------------- | | The event log on the server | The `AuthedApi` stub | | The cursor, in client-side state | The `Subscription` stub | | The token, in client-side state | The authenticated user held on the server object | | | Any call in flight | The **Call a stub from the old session** button makes the second column concrete. It holds on to the `AuthedApi` from before the drop and calls `whoami()` on it. That call does not hang and does not quietly reconnect. It rejects: ```js const stub = this.#authed ?? this.#staleAuthed; try { const user = await stub.whoami(); return `stub still works: ${user.name}`; } catch (error) { return `stub is broken: ${error.message}`; } ``` There is no automatic reconnection in Cap'n Web, and this is why: the library cannot know whether the object a stub pointed at still exists, still means the same thing, or should still be reachable by you. Recovery is a decision only the application can make. ## Why the log lives outside the session The server's API object is created fresh for every connection, and the authenticated user lives on the object that `authenticate()` returns. That is the object-capability pattern doing its job: the token crosses the wire once, and after that, holding the stub *is* the authorization. But it means all of that state dies with the socket. Anything that has to outlive a disconnect has to be somewhere else, which is why `createEventLog()` is called at module scope and passed in: ```js const log = createEventLog(); export function createMain() { return new PublicApi(log); } ``` :::caution Module scope is the right shape and the wrong storage. It lives as long as the isolate, and two clients can easily land on two different isolates. In a real deployment the log belongs somewhere addressable: a [Durable Object](/servers/workers/), a database, a queue. It must not live *in the session*. ::: ## Resuming without a gap The subscription takes the id of the last event the client actually processed: ```js subscribe(sinceId, sink) { const from = sinceId ?? this.#log.latestId(); // Stubs received as parameters are disposed when the call returns, so a // callback that will be used later has to be duplicated first. return new Subscription(this.#log, sink.dup(), from); } ``` **The cursor is the client's, not the server's.** It is a plain number in client-side state, which is exactly why it survives; a stub could not. Design the API so the caller can say where it left off, and reconnection becomes a normal operation rather than a recovery procedure. **`sink` is a callback going the other way.** The client passes an `RpcTarget`, the server receives a stub for it, and calling a method on that stub is an RPC back into the browser. That is all server-initiated messaging is here; there is no separate subscription mechanism. **The `.dup()` is mandatory.** Stubs arriving in parameters are disposed when the call returns, so holding one past that requires duplicating it. The `Subscription` disposes its copy in `[Symbol.dispose]()`, which also runs when the session dies, and that is what stops the timer on an abrupt disconnect. ## Replay has to be bounded A resume token from a client that has been gone for a week is a request to replay a week. The server caps it and tells the client when it has fallen too far behind: ```js const from = Math.max(sinceId, latest - MAX_REPLAY); return { events, truncated: from > sinceId }; ``` The client surfaces that as a gap rather than pretending it received everything. An unbounded replay is a denial-of-service vector. See [Security considerations](/guides/security/). ## How this page runs The other two playgrounds shim `fetch`. A WebSocket upgrade cannot be expressed that way inside a page, so this one replaces the `WebSocket` constructor for `/ws` and returns one end of a pair whose other end is handed to a real session: ```js function Shim(url, protocols) { if (new URL(url, location.href).pathname !== WS_PATH) { return new NativeWebSocket(url, protocols); } const { client, server } = connectedPair(String(url)); newWebSocketRpcSession(server, createMain(ENV)); return client; } ``` This skips the Worker's `fetch` handler, so upgrade handling is the one part of the example the page does not exercise. It keeps the API implementation, the session, the wire protocol, calls in both directions, and a connection that can genuinely be severed, which is the only thing this example is really about. ## Run it yourself ```sh npm run build # the examples resolve capnweb to dist/ npx wrangler dev --cwd examples/session-recovery --ip 127.0.0.1 --port 8789 ``` That version uses a WebSocket to a Worker, so you can also disconnect it by turning off your network. ## Next - [Sessions & reconnection](/guides/sessions/): the patterns here, written out in full. - [Disposal](/concepts/disposal/): why `.dup()` is needed and when disposers run. - [WebSocket transport](/transports/websocket/): what this example is running on. # Workers + React > A React app calling a Cap'n Web Worker, with a request timeline and runtime validation at the RPC boundary. Source: https://capnweb.com/examples/worker-react/ · Markdown: https://capnweb.com/examples/worker-react/index.md import { exampleBySlug } from '../../../examples.ts'; The same comparison as the [batch + pipelining example](/examples/batch-pipelining/), but from a real front end: a React app served as static assets by the same Worker that answers its RPC calls. It draws a timeline of the requests, so you can watch the sequential version wait out three round trips while the pipelined version makes one. It also shows the two halves of runtime validation, `@validateRpc()` on the server and `validateStub()` on the client, including what a rejected call looks like. :::note[There is no server behind this page.] The Worker is bundled into the page and answers its own requests, with the simulated latency from its `wrangler.jsonc`. The POST counts and the validation error are real: see [how the playground works](/examples/batch-pipelining/#how-this-page-runs). ::: ## One Worker, both jobs The Worker serves the built React app *and* the RPC endpoint. Static assets are matched first, so `fetch` only ever sees `/api`: ```ts export default { async fetch(request: Request, env: Env) { const url = new URL(request.url); if (url.pathname === '/api') { return newWorkersRpcResponse(request, new Api(env)); } return new Response('Not found', { status: 404 }); }, }; ``` The client points at a relative `/api`, so the same build works when served by the Worker and when served by the Vite dev server, which proxies `/api` across: ```ts const api = validateStub(newHttpBatchRpcSession('/api')); ``` ## Typed end to end, checked at runtime `runs.ts` imports the `Api` class from `server/worker.ts` **as a type**. That gives the client full autocomplete and compile-time checking against the real server interface, with no schema, no codegen step, and nothing shipped to the browser. The import disappears at build time. Types alone stop at the network boundary though, since anything can POST to `/api`. That is what the validation layer is for: - `@validateRpc()` on the server generates argument and return validators from the TypeScript types, and rejects malformed calls before they reach your method. - `validateStub()` on the client checks that what came back matches what the types promised. The **Test validation failure** button calls `authenticate(12345)` with a number where a string is declared, so you can see the server refuse it. :::note Validation is opt-in and lives in a separate package, `capnweb-validate`. Cap'n Web itself does not require it. See [runtime validation](/guides/validation/). ::: ## Run it yourself ```sh npm run build # the examples resolve capnweb to dist/ npx wrangler dev --cwd examples/worker-react --ip 127.0.0.1 --port 8787 ``` That serves it from a Worker, so the round trips cross the network. For React hot reloading, run the Worker and the Vite dev server side by side. See the [example's README](https://github.com/cloudflare/capnweb/tree/main/examples/worker-react). ## Next - [Runtime validation](/guides/validation/): the validation package in full. - [Cloudflare Workers](/servers/workers/): serving Cap'n Web from a Worker. - [RpcPromise & pipelining](/concepts/promises/): the mechanism being demonstrated. # How It Compares > Cap'n Web against tRPC, JSON-RPC, GraphQL, Cap'n Proto and the older distributed-object systems, including the things it deliberately does not do. Source: https://capnweb.com/guides/comparisons/ · Markdown: https://capnweb.com/guides/comparisons/index.md Cap'n Web claims to be more expressive than most RPC systems. This page is the receipt: what that buys you against each of the usual alternatives, and where the claim runs out. ## vs. tRPC, oRPC, and friends [tRPC](https://trpc.io/), [oRPC](https://orpc.unnoq.com/) and similar libraries share a lot with Cap'n Web: TypeScript inference instead of code generation, and no separate IDL to compile. The difference is what a call can *return*. | | Cap'n Web | Typical TS RPC library | | --------------------------------- | ----------------- | -------------------------- | | TypeScript types as the contract | Yes | Yes | | Separate IDL and codegen step | No | No | | Runtime validation of inputs | Opt-in, see below | Usually built in | | Return an **object** by reference | Yes | No, results are plain data | | Pass a **function** by reference | Yes | No | | Server calls the client | Yes | Subscriptions only | | Dependent calls in one round trip | Yes | No | | Reference lifetime management | Yes | N/A | One row there goes against us, and it is worth being straight about. "No schema language" is often claimed for this whole family, but it is only true of the *transport contract*. In practice a tRPC or oRPC procedure declares its input with a schema library, usually [Zod](https://zod.dev/) or anything else implementing [Standard Schema](https://standardschema.dev/), and the TypeScript type is inferred *from* that schema: ```ts // tRPC: the schema is the contract, and the static type is derived from it. publicProcedure.input(z.object({ id: z.string() })).query(({ input }) => getUser(input.id)); ``` So those libraries validate arriving data by default, and Cap'n Web does not. A Cap'n Web method signature is erased at runtime like any other TypeScript, and nothing checks the values against it unless you arrange for that. The direction of derivation is simply reversed: they generate types from a schema, while [`capnweb-validate`](/guides/validation/) generates the checks from your TypeScript signatures at build time. Either way you describe the boundary once, but with Cap'n Web it is a step you have to take. See [Types are not validation](/guides/security/#types-are-not-validation). Those libraries can batch calls, but batching and pipelining solve different problems. Batching combines calls that are **independent**: you already know all the arguments. Pipelining combines calls that are **dependent**, where the argument to the second call is the result of the first. That is the case that otherwise forces a round trip, and it is the case [`.map()`](/concepts/map/) and [`RpcPromise`](/concepts/promises/) exist to collapse. ## vs. JSON-RPC [JSON-RPC](https://www.jsonrpc.org/specification) is also JSON over any transport, and it also supports notifications in both directions. What it has no concept of: - **Pass-by-reference.** Every JSON-RPC method is addressed by a global name and every argument is plain data. There is no way to hand the other side a reference to one particular object and let them call methods on it, which is the whole basis of [capability-based authorization](/guides/security/). - **Lifetime management.** Nothing in JSON-RPC tracks that you are holding something the peer must keep alive, so there is nothing to release. Cap'n Web has [import/export tables and disposal](/concepts/disposal/). - **Pipelining.** No way to refer to the result of a call you have not received yet. Cap'n Web's closest relative is not JSON-RPC but CapTP, the object-capability protocol family that [Cap'n Proto](https://capnproto.org) also belongs to. ## vs. GraphQL, and the N+1 question GraphQL and Cap'n Web attack the same problem from opposite ends. GraphQL gives the client a query language so it can describe a whole dependent graph in one request. Cap'n Web gives the client promise pipelining so it can *write ordinary code* that happens to produce one request. The comparison is aggressive, though, and it breaks down in places. :::caution[`.map()` does not remove N+1; it relocates it] Pipelining collapses **network** round trips. It does not collapse **database** queries. ```ts // One network round trip. Still N+1 queries on the server. let names = await api.listUserIds().map(id => api.getUserName(id)); ``` The client waits once instead of N+1 times, which is a real and often dominant win. But the server still runs one `listUserIds` query and N `getUserName` queries. **Whether that second half matters depends on where your database is.** If it is across a network, you have moved the problem rather than solved it, and you want a batched method. If it is [SQLite embedded in a Durable Object](#where-n1-stops-mattering), those N queries are in-process function calls and N+1 is a normal way to write code. Read on; that case is the interesting one. ::: Things GraphQL has that Cap'n Web does not: - **A DataLoader equivalent.** There is no built-in batching or per-request caching layer to fold those N queries into one. If you need that, expose a method that takes the whole array and does a single `WHERE id IN (...)`, then call *that* from the map callback. - **Query cost analysis.** A GraphQL server can inspect a query and reject it as too expensive before executing any of it. Cap'n Web has no query planner, so there is nothing to analyse. Rate limiting is your job. See [Security considerations](/guides/security/). ### Where N+1 stops mattering The N+1 problem is not really about the number of queries. It is about the number of **round trips**, and a query is only expensive because the database is usually on the other side of a network. Take that network away and the arithmetic changes. With SQLite embedded in a [Durable Object](/servers/workers/), the database lives in the same process as your code, so a query is a function call measured in microseconds. SQLite's own documentation makes the argument directly: [many small queries are efficient in SQLite](https://www.sqlite.org/np1queryprob.html), and N+1 is not an anti-pattern there. Pair that with pipelining and both halves are gone: `.map()` removes the client's N round trips, and in-process SQLite removes the server's. The `getUserName` loop above stops being something to engineer around and becomes what it looks like, a loop. The two ideas are also not mutually exclusive. Nothing stops you exposing a GraphQL-style `query(document)` method over a Cap'n Web session, or using Cap'n Web for the interactive, capability-bearing parts of an app and GraphQL for the reporting queries. ## vs. Cap'n Proto, and using Cap'n Web from other languages Cap'n Web is **deliberately scoped to JavaScript and TypeScript.** It is not a port of Cap'n Proto and the two do not interoperate on the wire. See [the comparison table in the introduction](/start/introduction/#how-it-compares). If your backend is not JavaScript, the answer today is to use Cap'n Proto instead. It is the same object-capability model with the same promise pipelining, plus schemas and code generation for a long list of languages. A proxy that translated between the two given a Cap'n Proto schema would be a lovely thing to have; it does not exist. ### Why not a port? Cap'n Web's implementation works by walking arbitrary objects at runtime without knowing their types; that is what lets it serialize anything and forward any call without a schema. That is natural in a dynamic language and awkward in a static one. - **Another dynamic language** (Python, Ruby) would probably port fine. - **A statically-typed language** is much harder, because the type-agnostic object walking has no direct equivalent. - **A shared Rust/WASM core** does not obviously help either. The values Cap'n Web moves are JavaScript objects, so such an implementation would spend most of its size marshalling values across the JS/WASM boundary, plausibly more code than the entire TypeScript implementation, which is [%BUNDLE_SIZE%](/start/introduction/) in total. ## Isn't this distributed objects all over again? CORBA, Java RMI and .NET Remoting all tried to make remote objects work, and all are cautionary tales. It is a fair challenge, and Cap'n Web is making a specific bet about *why* they failed. The usual diagnosis is that they tried to make a remote call look exactly like a local call, to hide the network. That cannot work, because the differences are not cosmetic: remote calls have latency, they fail independently of your process, and the thing on the other end has a lifetime you do not control. Cap'n Web does not hide any of those: | Reality of the network | How it surfaces in Cap'n Web | | ---------------------- | --------------------------------------------------------------------------------------------- | | Latency | Every call returns an [`RpcPromise`](/concepts/promises/). You can see every place you wait. | | Partial failure | A dropped session [breaks every stub](/guides/sessions/) and rejects pending calls. | | Remote lifetime | [Disposal](/concepts/disposal/) is explicit; there is no distributed GC pretending otherwise. | The second failure was being **synchronous first.** In CORBA a call blocked until it returned, so a chain of N dependent calls cost N round trips, which made fine-grained object graphs unusable over a network and pushed everyone toward coarse, chatty-avoiding "service" interfaces. Promise pipelining inverts that: fine-grained interfaces are the ones that pipeline well. The third was sheer size. Cap'n Web is a single dependency-free package with a [wire protocol](/reference/protocol/) you can read in one sitting. None of this makes distributed systems easy. You still have to decide what happens on reconnect and how your API evolves (see [Sessions & reconnection](/guides/sessions/)). ## Is it a protocol, or a JavaScript library? Both. The `capnweb` npm package is one implementation; the [wire protocol](/reference/protocol/) is a specification you can implement yourself, which is what you would do to build an interoperating peer. The protocol is JavaScript-flavoured to roughly the same extent JSON is. Its value types are the JavaScript built-ins, but nothing about the framing, the import/export tables or the expression language requires a JavaScript peer. The one genuinely language-dependent corner is *producing* a [`.map()`](/concepts/map/) recording. The `["remap", ...]` expression that goes over the wire is plain data, so any implementation can **evaluate** one. Turning a natural-looking lambda into that data structure is the hard part, and JavaScript can only do it by [record-replay](/concepts/map/#how-the-heck-does-that-work) because it cannot reflect on a function body. A language with first-class expression trees, such as C#, could build the same structure directly from a lambda. # Security Considerations > Authentication over WebSocket, denial-of-service from pipelining, payload limits, and why types are not validation. Source: https://capnweb.com/guides/security/ · Markdown: https://capnweb.com/guides/security/index.md Cap'n Web is an object-capability system, which gives you strong tools for authorization, but there are a handful of things you must get right yourself. ## Authenticate in-band, not with cookies The WebSocket API in browsers always permits cross-site connections, and does not permit setting headers. Because of this, you generally **cannot use cookies nor other headers for authentication.** Instead, we highly recommend authenticating in-band, via an RPC method that returns the authenticated API: ```ts interface PublicApi { // Authenticate the API token, and return the authenticated API. authenticate(apiToken: string): AuthedApi; // Doesn't require authentication. getUserProfile(userId: string): Promise; } ``` ```ts // The client never gets an AuthedApi without presenting a valid token. using api = newWebSocketRpcSession('wss://example.com/api'); using authed = api.authenticate(apiToken); ``` On the server, `authenticate()` checks the credential once and returns a **new object holding the result**: ```ts class PublicApi extends RpcTarget { authenticate(apiToken: string): AuthedApi { let user = verifyToken(apiToken); // throws if invalid return new AuthedApi(user); } } class AuthedApi extends RpcTarget { constructor(private user: User) { super(); } // No token, no re-check. Holding this object is the proof. getUserId() { return this.user.id; } } ``` This is the object-capability pattern doing real work: the returned `AuthedApi` stub *is* the authorization. There is no ambient authority to confuse, and no way to call an authenticated method without holding the capability. Thanks to [pipelining](/concepts/promises/), it also costs no extra round trip. Yes, this means the server holds state, but only in memory, and only for the lifetime of that one session: the WebSocket connection, or the single HTTP batch. Nothing is persisted, and there is no session store to secure or expire. See [Sessions & reconnection](/guides/sessions/). ## Rate-limit, because pipelining is cheap for attackers Cap'n Web's pipelining can make it easy for a malicious client to enqueue a large amount of work to occur on a server, in a single message. To mitigate this, implement **rate limits on expensive operations**. Note that limits applied by a load balancer or gateway will not help here: they count requests or frames, and pipelining makes one frame arbitrarily expensive. The limit has to live in the application. Two amplifiers worth knowing about: - **Nested `.map()` multiplies.** A map over N elements whose callback maps over M produces N × M server-side calls from one client message. Unbounded *recursion* is less dangerous than it looks: [the recording is built on the caller's stack](/concepts/map/#nesting-and-recursion), so a runaway callback overflows the client first. But a deliberately crafted deep recording is not self-limiting. - **Un-awaited calls accumulate.** Every outstanding promise and every stub the peer holds pins an entry in your export table, and the object behind it, for the life of the session. A peer that never settles or disposes anything grows your memory monotonically. There is no library setting for this. `RpcSessionOptions.limits` covers message size, nesting depth and bigint digits (not reference counts), so if you need a bound on how much one session can pin, you have to enforce it in your own code. Attaching disposers to the objects you return gives you something to count. If using Cloudflare Workers, also consider configuring [per-request CPU limits](https://developers.cloudflare.com/workers/wrangler/configuration/#limits) to be lower than the default 30s. Note that in stateless Workers (that is, not Durable Objects), the system considers an entire WebSocket session to be one "request" for CPU limit purposes. ## Set transport payload limits Cap'n Web applies receiver-side resource limits before expensive message processing, including a maximum incoming message size before `JSON.parse`. If your app is exposed to untrusted peers, **also configure native transport or socket payload limits where available**: | Runtime | Option | | ----------------- | ------------------------------------------------ | | Node.js `ws` | `new WebSocketServer({ maxPayload })` | | Bun | `Bun.serve({ websocket: { maxPayloadLength } })` | | Browsers / others | The runtime's built-in WebSocket cap | Cap'n Web's own check runs *after* `RpcTransport.receive()` has returned a complete message string, so transport-level limits are still the first line of defence against buffering very large frames. ## Types are not validation Cap'n Web currently does not provide any runtime type checking. When using TypeScript, keep in mind that **types are checked only at compile time**. A malicious client can send types you did not expect, and this could cause your application to behave in unexpected ways. For example, MongoDB uses special property names to express queries; placing attacker-provided values directly into queries can result in query injection vulnerabilities, similar to SQL injection. Of course, JSON has always had the same problem, and there exists tooling to solve it. Can a peer pass a callback where you declared a `string`? Yes. It will arrive as an `RpcStub`, your code will do something surprising with it, and TypeScript will have told you nothing. Validate at the boundary. ### Use `capnweb-validate` The companion package [`capnweb-validate`](/guides/validation/) is the recommended answer, and it is built for exactly this problem. It keeps your **TypeScript method signatures as the source of truth** and generates the runtime checks from them at build time, so the boundary is described once rather than twice: ```ts import { validateRpc } from 'capnweb-validate'; @validateRpc() export class Api extends RpcTarget { // Arguments are checked against these types before the method body runs. getUser(id: string, opts: { includeEmail: boolean }) { // ... } } ``` Two properties make it worth reaching for over hand-written checks: - **Every method is covered.** Validation is applied to the class, so a method added next year is checked without anyone remembering to check it. Hand-rolled guards protect only the boundary someone thought about. - **It fails closed.** If the decorator is left untransformed because the bundler plugin is not wired up, it throws a configuration error at startup rather than quietly running unvalidated. You cannot ship a service that only looks validated. See [Runtime Validation](/guides/validation/) for setup. A general-purpose schema library such as [Zod](https://zod.dev/) works too, and is the better choice if you already validate with one elsewhere in the codebase, or if you need constraints a type cannot express, like "a string of at most 200 characters" or "a positive integer". The two compose: derive the shape from the types, then apply your own checks to the values. In the future we hope to explore auto-generating type-checking code based on TypeScript types in the core library. ### What the protocol does guarantee Type confusion is your problem, but prototype pollution is not. The protocol hardens two things regardless of what you do: - **`Object.prototype` members are unreachable.** Any property name that exists on `Object.prototype` (`constructor`, `__proto__`, `valueOf`, `hasOwnProperty` and friends) is blocked both when resolving a property path and when deserializing an object literal. This holds even if the target object has legitimately overridden the name. - **`toJSON` is stripped on the way in.** It is not an `Object.prototype` member, but it would let a peer influence how your values serialize, so an incoming object carrying one has it removed. Note that this applies to deserialization only, not to property paths. - **Array paths accept only non-negative integer indices**, matching what serialization can produce. What is reachable *on* an object depends on what kind of object it is, and the two rules are opposites: an `RpcTarget` exposes its **prototype** members and explicitly refuses instance properties, while a plain object exposes its **own** properties only. That distinction decides where it is safe to put a secret, so read [RpcTarget](/concepts/rpc-target/) rather than guessing. ## `private` and `.map()` **`private` is not private.** TypeScript's `private` is erased at runtime and does not hide a method from RPC. Use `#`-prefixed names for genuinely private members. See [RpcTarget](/concepts/rpc-target/). **Stubs captured by `.map()` are handed to the peer.** Any stubs you use in a `.map()` callback, and any parameters you pass to them, are sent to the peer, and a malicious peer can use them for anything, not just calling your callback. Typically it only makes sense to invoke stubs that came from that same peer originally. See [The magic `map()`](/concepts/map/). ## Reporting vulnerabilities Please report security issues in Cap'n Web according to the [project's security policy](https://github.com/cloudflare/capnweb/blob/main/SECURITY.md). # Sessions & Reconnection > How long RPC state lives, what a dropped connection destroys, how to reconnect and resume, and how to evolve and scale a Cap'n Web service. Source: https://capnweb.com/guides/sessions/ · Markdown: https://capnweb.com/guides/sessions/index.md Cap'n Web keeps state, but only for the life of one session, and never on disk. Understanding exactly how long "one session" is answers most operational questions about it. ## Nothing is persistent Each side of a session maintains [import and export tables](/reference/protocol/) mapping IDs to live objects. Those tables exist only in memory, only for that session: | Transport | A session lasts | | ---------------------------------------- | ------------------------------ | | [WebSocket](/transports/websocket/) | The lifetime of the socket | | [HTTP batch](/transports/http-batch/) | A single HTTP request/response | | [MessagePort](/transports/message-port/) | The lifetime of the port | So there is no persistence story, because there is nothing to persist. You do **not** need a database, a session store, or a serialization format for the tables. You could not write one anyway. An export ID is a reference to a live object in a live process. Serializing it would be like serializing a file descriptor. Server-side state naturally attaches to the objects you export, and dies with them: ```ts class PublicApi extends RpcTarget { authenticate(token: string): AuthedApi { let user = verifyToken(token); // throws if bad return new AuthedApi(user); // state lives on this object } } class AuthedApi extends RpcTarget { constructor(private user: User) { super(); } getUserId() { return this.user.id; } // no token re-check needed } ``` The client's ability to call `getUserId()` *is* the `AuthedApi` reference it holds. That object (and the `user` it closed over) lives until the session ends or the client disposes the stub. On an HTTP batch it lives for a few milliseconds. See [Security considerations](/guides/security/#authenticate-in-band-not-with-cookies). ## Design for the session going away Because a session can end at any moment: :::tip **It must always be possible to reconnect and reconstruct.** Never design an interaction where losing the session part-way through leaves the client unable to recover, or the system in a state nobody can repair. ::: In practice that means: - Don't hand out a capability that can only ever be obtained once. If the client's only route to some object is a one-shot method, a dropped socket strands them permanently. - Make mutations idempotent, or give them a client-supplied ID, so a retry after an ambiguous failure is safe. - Anything long-running should be resumable from a checkpoint the client already knows about. ## Reconnecting Cap'n Web does not reconnect automatically, and it deliberately does not try to re-establish your stubs for you: it cannot know whether the objects they referred to still make sense. When a session drops, **every stub from that session is permanently broken.** Pending calls reject, and new calls on old stubs fail immediately. Detect it with `onRpcBroken`: ```ts stub.onRpcBroken((error) => { console.error('connection lost:', error); }); ``` Recovery means creating a new session and calling the methods again to get fresh objects. The pattern that makes this bearable is to have exactly one place that owns the root stub, and derive everything else from it: ```ts function connect(): RpcStub { return newWebSocketRpcSession('wss://example.com/api'); } ``` ### The React pattern Hold the root stub in state at the top of the tree and pass it down as a prop. Child components call the methods they need off that stub rather than storing sub-stubs of their own. ```tsx function connect(onBroken: () => void): RpcStub { let api = newWebSocketRpcSession('wss://example.com/api'); api.onRpcBroken(onBroken); return api; } function App() { let [api, setApi] = useState(() => connect(reconnect)); function reconnect() { // The thunk is load-bearing -- see below. setApi(() => connect(reconnect)); } return ; } ``` On reconnect you set a *new* root stub, React re-renders the tree, and every child re-derives its own capabilities from the new session. There is no per-component reconnection logic, and no risk of a component holding a stub from the previous session. :::danger[Three things that will bite you here] **A stub is callable.** `RpcStub` is a `Proxy` whose target is a function, so `typeof stub === 'function'` is true. React's state setters treat a function argument as an *updater callback*, which means `setApi(newStub)` calls your stub instead of storing it; because the call returns an `RpcPromise` rather than throwing, you get a rejected promise in state and no obvious error. Always `setApi(() => newStub)`. **Don't dispose the session in an effect cleanup.** Disposing the root stub closes the connection. React StrictMode runs effects mount → cleanup → mount in development, so a cleanup that disposes would tear down a session the remounted component then keeps using, and every later call throws. Tie disposal to real unmount or page unload, not to an effect. (StrictMode also double-invokes `useState` initializers, so expect one extra socket in development.) **`onRpcBroken` cannot be unregistered.** It returns nothing, and registering twice on the same stub fires twice. Register it where the session is created (as `connect()` does above) rather than in an effect that might re-run. ([#234](https://github.com/cloudflare/capnweb/issues/234) proposes returning a disposable handle.) ::: ### Resumable subscriptions A subscription that just pushes events will silently lose whatever happened while the client was disconnected. Design the API so the caller can say where it left off: ```ts interface AuthedApi { // Deliver every event after `sinceId`, then keep streaming live ones. subscribe(sinceId: string | null, sink: EventSink): void; } ``` On reconnect the client passes the ID of the last event it actually processed, and the server replays the gap. This costs you nothing when nothing was missed, and is the difference between a subscription that survives a train tunnel and one that does not. ## Versioning and deploys Cap'n Web has no schema, so it also has no schema-evolution mechanism: no field numbers, no reserved tags, no wire-level compatibility rules to learn. The rules are the ones you already know for **evolving a JavaScript API without breaking existing callers.** | Safe | Breaking | | --------------------------------------------- | -------------------------------------- | | Add a new method \* | Rename or remove a method | | Add a new **optional** parameter at the end | Add a required parameter | | Add a property to a returned object | Remove or rename a returned property | | Accept a wider type than before | Accept a narrower type than before | | Return a new capability alongside the old one | Change what an existing method returns | \* These are the rules for Cap'n Web itself. If you use [`capnweb-validate`](/guides/validation/), its generated validators are stricter; a peer whose validator was built before you added a method will refuse the call. Its own compatibility table is under [Schema evolution](/guides/validation/#schema-evolution), and you should read both. Two deployment realities to plan for: - **Both versions run at once** during a rolling deploy, so a client may talk to an old instance on one connection and a new one on the next. - **WebSocket clients can be very old.** A browser tab left open for a week is still holding a session against whatever you deployed a week ago. Add capabilities; don't take them away. ## Load balancing and scaling Nothing persists, but a WebSocket session *is* in-memory state, which means it is pinned to one process for its lifetime. The consequences are the ordinary ones for stateful connections, plus one that is specific to pipelining. - **Every frame of a socket must reach the same backend.** Any load balancer that routes a WebSocket as a single connection already does this. Do not put a session behind something that can re-route mid-stream. - **Scale-in is the awkward part.** Long-lived connections do not drain by themselves, so an instance can stay alive for hours waiting for the last tab to close. Since clients must handle reconnection anyway, you can lean on it: cap session age, then close with a normal closure and let clients come back on a fresh instance. - **Request-count metrics will lie to you.** [Pipelining](/concepts/promises/) means one message can carry an enormous amount of work, so a load balancer counting requests, or a rate limiter counting frames, sees almost nothing. Rate-limit expensive *operations* inside the application. See [Security considerations](/guides/security/#rate-limit-because-pipelining-is-cheap-for-attackers). - **Budget memory per session.** Everything the peer holds a reference to is pinned in your export table until it is released, and the library has no export-count limit to set; bounding what a single session may accumulate is your own bookkeeping. See [Security considerations](/guides/security/). [HTTP batch](/transports/http-batch/) sidesteps all of this: a batch is one request, any instance can serve it, and everything is released when the response is written. It is the right transport for a stateless edge deployment. On Cloudflare Workers, a [Durable Object](/servers/workers/) gives a session a natural, addressable home. # Runtime Validation > Generate runtime validators from your TypeScript types at build time with capnweb-validate. Source: https://capnweb.com/guides/validation/ · Markdown: https://capnweb.com/guides/validation/index.md Your method signature says `id: string`. Nothing stops a peer from sending an array, an object with a `$ne` property, or a callback that arrives as an `RpcStub`. TypeScript is erased long before the call does, so at runtime that signature is a comment. [`capnweb-validate`](https://www.npmjs.com/package/capnweb-validate) makes it enforceable. Mark a class with `@validateRpc()`, and at build time a bundler plugin (or the CLI) reads the resolved TypeScript types and injects a validator for each method, which runs before your code does: ```ts @validateRpc() export class Api extends RpcTarget { // A caller sending anything but a string now gets an error, not your method body. getUser(id: string) { return this.db.find(id); } } ``` You do not write a schema. The types you already wrote are the schema. :::note If a validation decorator is left untransformed, it throws a configuration error rather than silently running without validation. You cannot accidentally ship an unvalidated service. ::: ## Does this mean defining my API twice? No, and this is the reason `capnweb-validate` exists in this shape. "Schemaless" means the *library* needs no schema: Cap'n Web forwards whatever call you make without being told about it in advance. It does not mean you have no contract. Your contract is the TypeScript interface, used on both ends. The only problem is that TypeScript is erased before your code ever meets a hostile input. There are two honest ways to close that gap without writing the interface out twice: - **Generate the validators from the types.** That is what `capnweb-validate` does: the TypeScript signature stays the single source of truth and the runtime check is derived from it at build time. - **Generate the types from the validators.** Schema libraries like [Zod](https://zod.dev/) infer TypeScript types from the schema object, so you write the schema and get the types for free. [ArkType](https://arktype.io/), [typia](https://typia.io/) and [ts-runtime-checks](https://github.com/GoogleFeud/ts-runtime-checks) occupy similar territory, the last two also transforming TypeScript types directly into checks. Either way you write one description of the boundary, not two. What you must not do is write only the TypeScript and assume it is doing something at runtime. ## Install Two packages, or one if you are on Workers RPC: ```sh npm install capnweb capnweb-validate ``` Workers RPC users can install `capnweb-validate` without installing `capnweb`. The root package has no runtime dependency on `capnweb`; Cap'n Web-specific helpers live under `capnweb-validate/capnweb`. There is no TypeScript peer dependency to satisfy. Reading your resolved types needs a compiler with the JavaScript API, so the package depends on `typescript` (`>=5.7.0 <7`) directly and uses that copy. This is what keeps the transform working in a TypeScript 7 (`tsgo`) workspace, where the compiler your editor and `tsc` use no longer exposes that API. ## Server usage Decorate the class you expose. Every call that arrives is checked against the method's declared parameter types before your code runs: ```ts import { newWorkersRpcResponse, RpcTarget } from 'capnweb'; import { validateRpc } from 'capnweb-validate'; type User = { id: string; name: string }; @validateRpc() export class Api extends RpcTarget { async authenticate(sessionToken: string): Promise { // ... } } export default { async fetch(request: Request, env: Env) { return newWorkersRpcResponse(request, new Api()); }, }; ``` `@validateRpc()` validates calls on class instances, so it works with Cap'n Web, Workers `WorkerEntrypoint`, and Workers `DurableObject` services. With no explicit type argument, the RPC surface is the class's public string-named methods and RPC-readable getters/properties, matching Cap'n Web dispatch. `implements SomeInterface` can sharpen matching signatures, but it does **not** hide extra public class methods. Keep local-only helpers private or symbol-named. An explicit `@validateRpc()` makes `SomeInterface` the RPC surface. Public class methods outside that interface are rejected over RPC. ## Client usage Client-side stub validation is explicit. Wrap a client stub with `validateStub()` when the caller wants return values and pipelined calls checked against a concrete surface: ```ts import { newHttpBatchRpcSession } from 'capnweb'; import { validateStub } from 'capnweb-validate'; import type { Api } from './worker'; export const api = validateStub(newHttpBatchRpcSession('/rpc')); ``` `validateStub()` validates resolved return values on the caller side. It does **not** validate outgoing arguments; the receiver validates those on arrival. ## Wiring it into your build ### Bundler plugins ```ts import capnwebValidate from 'capnweb-validate/vite'; // or import capnwebValidate from 'capnweb-validate/rollup'; // or import capnwebValidate from 'capnweb-validate/webpack'; // or import capnwebValidate from 'capnweb-validate/rspack'; // or import capnwebValidate from 'capnweb-validate/esbuild'; // or import capnwebValidate from 'capnweb-validate/farm'; export default { plugins: [capnwebValidate()], }; ``` The plugin transforms matching modules in memory; your source files are not modified on disk. ### CLI Wrangler does not expose a bundler plugin hook. For Wrangler, CI, or any flow that needs transformed files on disk: ```sh capnweb-validate build --out .capnweb-validate ``` | Option | Meaning | | ------------------- | ----------------------------------------------------- | | `--out ` | Where to write the transformed source tree. Required. | | `--tsconfig ` | Defaults to `./tsconfig.json`. | | `--cwd ` | Defaults to `process.cwd()`. | Point the downstream build tool at the generated entry under `--out`. ## Opting out per method `@skipRpcValidation()` exempts one method from an otherwise validated class: ```ts import { RpcTarget } from 'capnweb'; import { skipRpcValidation, validateRpc } from 'capnweb-validate'; @validateRpc() class Api extends RpcTarget { @skipRpcValidation() unsafe(payload: unknown): unknown { return payload; } } ``` The method still goes through Cap'n Web normally. This only disables `capnweb-validate` validation for that method. ## Validation errors Failures throw `TypeError`, so they keep their standard error type when crossing RPC boundaries. The message includes the failing path, expected type, and actual type. | Boundary | Failure | How it surfaces | | ------------- | --------------------- | ----------------------------------------------------------- | | Client stub | Bad resolved return | The returned promise rejects. | | Server target | Bad incoming argument | The server throws and the caller observes an RPC rejection. | ## Type coverage The supported set matches Cap'n Web's published wire format: every type Cap'n Web guarantees can travel over RPC also has a precise build-time validator. That includes primitives and literal types, arrays, tuples, `Map`/`Set`, plain object shapes, unions, `Record`/index signatures, `Promise` returns, and the RPC-compatible built-ins (`Date`, `ArrayBuffer`, typed arrays, `Error` subclasses, `Blob`, streams, `URL`, `Headers`, `Request`, `Response`). Pass-by-reference values are validated as stubs: functions, `RpcStub`, `RpcPromise`, `RpcTarget` subclasses, and Workers `Fetcher`. These are rejected **at build time** so you find out before the first RPC call: | Type | Reason | | ------------------- | ------------------------------------- | | `WeakMap` | Not a supported RPC validation type. | | `WeakSet` | Not a supported RPC validation type. | | `SharedArrayBuffer` | Not a supported RPC validation type. | | `File` | Use a `Blob` or `Uint8Array` instead. | Overloaded methods are passed through unvalidated with a warning. Validating against one signature would reject valid calls to the others. Collapse the overloads into a single signature with union parameters, or use `@skipRpcValidation()` to silence the warning. For generics, the transform emits one validator at the class declaration, so it cannot specialize per-`new`-expression. Use an explicit surface such as `@validateRpc>()` when the type arguments are known at the decorator site. An unconstrained type parameter defaults to `any` with a warning; a constrained one validates against its constraint. ## Schema evolution A validator built from one version of your types will eventually meet a peer built from another. Additive changes go through; changes that would let an unchecked value reach your code do not: | Change | Result | | -------------------------------------- | ------- | | Extra argument | Allowed | | Extra object property | Allowed | | Extra index-signature key | Allowed | | New optional parameter or property | Allowed | | Missing required parameter or property | Refused | | Renamed or retyped member | Refused | | Changed tuple length, no rest element | Refused | | New union member | Refused | | New method | Refused | To remove a required member, make it optional in one release and delete it in a later one, so no build ever requires something a peer has already stopped sending. "Allowed" is not the same as "visible". Extra arguments are **dropped before the method runs**, so an implementation cannot read an argument no validator checked: ```ts // spec generated from: greet(name: string) greet(name: string, ...rest: unknown[]) { // rest is always empty } // spec generated from: sum(label: string, ...values: number[]) sum(label: string, ...values: number[]) { // gets every argument, each one validated } ``` Truncation only applies where the spec declares its parameters. A client-side spec omits `args` entirely, so nothing is dropped there. Extra *object properties*, by contrast, are forwarded to the implementation unvalidated; an index signature is the exception, since it validates every property outside the declared ones. Keep `strictNullChecks` on. Without it TypeScript erases `null` from your types, and the generated validator will refuse a `null` that a peer built with the flag on considers perfectly valid. Full details are in the [`capnweb-validate` README](https://github.com/cloudflare/capnweb/tree/main/packages/capnweb-validate). # Workers RPC Interop > How Cap'n Web interoperates with the RPC system built into the Cloudflare Workers Runtime, and where the two still differ. Source: https://capnweb.com/guides/workers-rpc/ · Markdown: https://capnweb.com/guides/workers-rpc/index.md Cap'n Web works on any JavaScript platform. But on Cloudflare Workers specifically, it's designed to play nicely with [the built-in RPC system](https://blog.cloudflare.com/javascript-native-rpc/). The two have basically the same semantics. The only fundamental difference is that Workers RPC is a built-in API provided by the Workers Runtime, whereas Cap'n Web is implemented in pure JavaScript. ## What interoperates - On Workers, the `RpcTarget` class exported by `capnweb` is just an **alias of the built-in one**, so you can use them interchangeably. - RPC stubs and promises originating from one RPC system can be **passed over the other**. This automatically sets up proxying. - You can also send Workers **Service Bindings** and **Durable Object stubs** over Cap'n Web; again, this sets up proxying. So basically, it "just works". ```ts import { RpcTarget, newWorkersRpcResponse } from 'capnweb'; export class Api extends RpcTarget { constructor(private env: Env) { super(); } // Hand a browser client a capability backed by a Durable Object. getRoom(name: string) { let id = this.env.ROOMS.idFromName(name); return this.env.ROOMS.get(id); // a DO stub, proxied over Cap'n Web } } ``` ## Compatibility date For best compatibility, set your [Workers compatibility date](https://developers.cloudflare.com/workers/configuration/compatibility-dates/) to at least `2026-01-20`, or enable the [compatibility flag](https://developers.cloudflare.com/workers/configuration/compatibility-flags/) `rpc_params_dup_stubs`. This aligns the Workers Runtime with Cap'n Web's stub ownership rules for call parameters. ## Where they still differ As of this writing the feature set is not exactly the same between the two. We aim to fix this over time, by adding missing features to both sides until they match. Expect Cap'n Web to run ahead. It is a library rather than a runtime built-in, so it can ship a new idea in a version bump instead of a compatibility flag, and that makes it the natural place to experiment. `.map()` is the current example: it exists in Cap'n Web and is on the list for Workers RPC. The intent is that the two converge, with Cap'n Web arriving first. | Capability | Cap'n Web | Workers RPC | | ------------------------------------------- | --------- | ----------- | | `Map` and some other built-ins | Not yet | Yes | | `Set` | Yes | Yes | | Values containing aliases and cycles | No | Yes\* | | `RpcPromise` in the parameters of a request | Yes | Not yet | | The magic `.map()` method | Yes | Not yet | | `onRpcBroken()` | Yes | Not yet | \* Workers RPC supports sending values that contain aliases and cycles. This can cause problems, so we plan to **remove** this feature from Workers RPC, with a compatibility flag, of course. [`onRpcBroken()`](/guides/sessions/#reconnecting) is worth calling out, because there is no clean way to reconstruct it. It is how you learn that a peer went away, which is what drives reconnection and what lets a server drop a subscription whose subscriber has vanished. Code holding a native Workers stub has to fall back to noticing that calls have started failing, or to watching for the disposer of a stub it handed out. ## When to use which - **Worker-to-Worker or Worker-to-Durable-Object**, inside Cloudflare: use built-in Workers RPC. It is faster and needs no library. - **Browser-to-Worker**, or anything crossing the public internet: use Cap'n Web. Workers RPC does not speak to browsers. - **Both**: mix freely. Stubs cross the boundary and Cap'n Web proxies them. # API Cheat Sheet > Every export of the capnweb package at a glance, with links to the page that explains it. Source: https://capnweb.com/reference/api/ · Markdown: https://capnweb.com/reference/api/index.md Everything below is exported from the `capnweb` package. ## Starting a session | Function | Use | | -------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | `newHttpBatchRpcSession(url, options?)` | Client. One HTTP request carrying a whole batch. [Docs](/transports/http-batch/) | | `newWebSocketRpcSession(urlOrSocket, localMain?, options?)` | Client *and* server. Long-lived bidirectional session. [Docs](/transports/websocket/) | | `newMessagePortRpcSession(port, localMain?, options?)` | Both ends. Web Workers, iframes. [Docs](/transports/message-port/) | | `new RpcSession(transport, localMain?, options?)` | Both ends, over any [custom transport](/transports/custom/). | `RpcSession` exposes `getRemoteMain(): T` to obtain a stub for the peer's main interface. ## Answering requests | Function | Runtime | | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- | | `newWorkersRpcResponse(request, api, options?)` | [Cloudflare Workers](/servers/workers/). Handles batch *and* WebSocket. | | `newHttpBatchRpcResponse(request, api, options?)` | Any Fetch-API runtime. [Deno](/servers/deno/), [Bun](/servers/bun/), [others](/servers/other/). | | `nodeHttpBatchRpcResponse(request, response, api, options?)` | [Node.js](/servers/node/) `http` module. | | `newBunWebSocketRpcHandler(factory)` | [Bun](/servers/bun/). Returns a `Bun.serve()` `websocket` handler. | | `newWebSocketRpcSession(socket, api, options?)` | Any runtime, given an open `WebSocket`. | ## Types and classes ### `RpcTarget` Base class marking instances as **pass-by-reference**. Callers reach prototype methods and getters, never instance properties. Names prefixed with `#` are never exposed. [Docs](/concepts/rpc-target/) ### `RpcStub` A `Proxy` standing in for a remote object. | Member | Meaning | | -------------------- | ---------------------------------------------------------------------------- | | *any method* | Invokes the corresponding method on the remote target. Returns `RpcPromise`. | | *any property* | Returns an `RpcPromise` for the remote property. | | `.dup()` | Independent duplicate; target released when all duplicates are disposed. | | `.onRpcBroken(cb)` | Called if the stub becomes permanently unusable. | | `[Symbol.dispose]()` | Release this stub. | `new RpcStub(target)` creates one locally, without a connection. [Docs](/concepts/stubs/) ### `RpcPromise` A thenable that is *also* a stub for its own eventual result. | Member | Meaning | | ------------------------ | ---------------------------------------------------- | | `await` / `.then()` | Resolve normally. | | *any method or property* | Pipelined, no round trip. | | `.map(fn)` | Transform the value remotely. [Docs](/concepts/map/) | | `.dup()` | Duplicate, usable immediately. | | `[Symbol.dispose]()` | Release; disposes the future result too. | `new RpcPromise(promise)` wraps a local `Promise` so callers can pipeline on it before it settles. It takes ownership of the resolution. [Docs](/concepts/promises/) ### `RpcTransport` Interface for custom transports. ```ts interface RpcTransport { send(message: string): Promise; receive(): Promise; abort?(reason: any): void; // Optional: "string" | "jsonCompatible" | "jsonCompatibleWithBytes" | "structuredClonable" encodingLevel?: string; } ``` [Docs](/transports/custom/) ### `RpcSessionOptions` Passed as the last argument to the session and response helpers. Commonly used for response `headers` (e.g. CORS) on the HTTP batch helpers. ## Disposal at a glance | You have | You must | | ---------------------------------------------------- | ------------------------------------------------------ | | A stub you created or received as a **return value** | Dispose it. | | A stub you passed as a **parameter** | Dispose your copy; the callee's copy is auto-disposed. | | A stub received as a **parameter**, needed later | `.dup()` it, then dispose the duplicate later. | | A promise you will never await | Dispose it (or use `using`). | | A property of a stub or promise | Nothing; dispose the parent. | | Anything, in an HTTP batch | Nothing; the batch end disposes everything. | [Full rules](/concepts/disposal/) ## Value types on the wire **By value:** primitives, plain objects, arrays, `Set`, `bigint`, `Date`, `ArrayBuffer`, `DataView`, typed arrays, `Error` and well-known subclasses, `Blob`, `ReadableStream`, `WritableStream`, `URL`, `RegExp`, `Headers`, `Request`, `Response`. **By reference:** `RpcTarget` subclasses, functions, existing stubs and promises. **`Set` elements:** stubs are supported. Promises and `Blob`s cannot be direct elements when sent over a connection, but may be nested inside another value. **Not supported:** `Map` (not yet); non-`RpcTarget` classes and cyclic values (intentionally). [Docs](/concepts/values/) # Wire Protocol > The complete Cap'n Web wire protocol, covering serialization, import/export tables, top-level messages, and expressions. Source: https://capnweb.com/reference/protocol/ · Markdown: https://capnweb.com/reference/protocol/index.md This page documents what actually goes over the socket. You do not need it to use Cap'n Web, but you do need it to implement an interoperating peer, or to debug traffic in a network inspector. ## Serialization The protocol uses JSON as its basic serialization, with a preprocessing step to support non-JSON types. Why not a binary format? While the author is a big fan of optimized binary protocols in other contexts, it cannot be denied that in a browser, JSON has big advantages. Being built into the browser gives it a leg up in performance, code size, and developer tooling. The usual argument for binary is size on the wire, and it is weaker here than it looks: - `JSON.parse` and `JSON.stringify` are native. A binary codec written in JavaScript has to beat optimized C++ from inside the JS engine, which is a hard start. - In a browser, **the code you ship is part of the cost**. A binary format that saves bytes per message but adds kilobytes to the bundle can easily lose, especially for an application that is not chatty. - The obvious redundancy (the same property names repeating in every message) is exactly what compression is good at. Where it is available, WebSocket `permessage-deflate` or HTTP content encoding removes most of it without the protocol having to. (Availability is not universal: Cloudflare Workers' `WebSocketPair` does not negotiate compression extensions.) You also get to read the traffic in your browser's network inspector, which is not nothing. Non-JSON types are encoded using arrays. The first element of the array contains a string type code, and the remaining elements contain the parameters needed to construct that type. For example, a `Date` might be encoded as: ```json ["date", 1749342170815] ``` To encode an array, the array must be wrapped in a second layer of array to create an array expression: ```json [["just", "an", "array"]] ``` ## Client vs. server The protocol does not have a "client" or a "server"; it is fully bidirectional. Either side can call interfaces exported by the other. With that said, for documentation purposes, we often use the words "client" and "server" when describing specific interactions, in order to make the language easier to understand. The word "client" generally refers to the caller of an RPC, or the importer of a stub. The word "server" refers to the callee, or the exporter. This is merely a convention to make explanations more natural. ## Transport and framing The protocol operates on a bidirectional stream of discrete messages. Each message is a single JSON value, typically an array. The protocol does not define how messages are framed on the wire; this is the responsibility of the transport layer. For transports that natively provide message framing, such as WebSocket or `MessagePort`, each transport-level message corresponds to exactly one RPC message. The built-in HTTP transport is **newline-delimited**, packing a series of messages into a single HTTP request or response body. Each message is serialized as a single line of JSON with no embedded newlines, and messages are separated by a newline character (`\n`). An empty body is interpreted as zero messages. Other transports are free to use other framing strategies. ## Imports and exports Each side of an RPC session maintains two tables: **imports** and **exports**. One side's exports correspond to the other side's imports. Imports and exports are assigned sequential numeric IDs. However, in some cases an ID needs to be chosen by the importing side, and in some cases by the exporting side. To avoid conflicts: - When the **importing** side chooses the ID, it chooses the next **positive** ID, starting from 1 and going up. - When the **exporting** side chooses the ID, it chooses the next **negative** ID, starting from -1 and going down. - ID **zero** is automatically assigned to the "main" interface. To be more specific: - The importing side chooses the ID when it initiates a call: the ID represents the result of the call. - The exporting side chooses the ID when it sends a message containing a stub: the ID represents the target of the stub. For comparison, in CapTP and Cap'n Proto there are four tables instead of two: imports, exports, questions, and answers. In this library, questions are unified with imports, and answers with exports. By convention, when describing the meaning of any RPC message, we always take the perspective of the sender. So if a message contains an "import ID", it is an import from the perspective of the sender, and an export from the perspective of the recipient. Note that IDs are never reused. This differs from Cap'n Proto, which always tries to choose the smallest available ID. We assume no session will ever exceed 2^53 IDs, so assigning sequentially is fine. ## Push and pull An RPC call follows this sequence: 1. The client sends the server a **push** message containing an expression to evaluate. - The push is implicitly assigned the next positive ID in the client's import table. - The expression expresses the call to make. - Upon receipt, the server evaluates the expression and delivers the call to the application. 2. The client subsequently sends a **pull** message specifying the import ID just created by the push. This expresses that the client is interested in receiving the result as a **resolve** message. 3. The client may subsequently refer to the import ID in pipelined requests. 4. When the server is done executing the call, it sends a **resolve** message specifying the export ID of the push and an expression for its result. 5. Upon receiving the resolution, the client no longer needs the import table entry, so it sends a **release** message. Upon receipt, the server disposes its copy of the return value, if necessary. Some notes: - The client does not need to send a pull message if it doesn't care to receive the results. In practice, if the application never awaits the promise, it is never pulled. **The promise can still be used in pipelining without pulling.** - Technically, the pushed expression can contain any number of calls, including none. A client could, for example, push a large data structure containing no calls, then subsequently make multiple calls that use this data structure via pipelining, avoiding sending the same data multiple times. - If the call throws an exception, the server sends a **reject** message instead of resolve. - Resolve and reject are the same messages used to resolve exported promises (that is, a promise introduced when it was sent as part of some other RPC message). Thus, calls and exported promises work the same. This differs from Cap'n Proto, where returning from a call and resolving an exported promise were entirely different messages, with a lot of duplicated semantics. ## Top-level messages The following are the top-level messages that can be sent over the RPC transport. ### push ```json ["push", expression] ``` Asks the recipient to evaluate the given expression. The expression is implicitly assigned the next sequential import ID, in the positive direction. The recipient evaluates the expression, delivering any calls therein to the application. The final result can be pulled, or used in promise pipelining. ### pull ```json ["pull", importId] ``` Signals that the sender would like to receive a resolve message for the resolution of the given import, which must refer to a promise. This is normally only used for imports created by a push, as exported promises are pulled automatically. ### resolve ```json ["resolve", exportId, expression] ``` Instructs the recipient to evaluate the given expression and then use it as the resolution of the given promise export. ### reject ```json ["reject", exportId, expression] ``` Instructs the recipient to evaluate the given expression and then use it to reject the given promise export. The expression is not permitted to contain stubs. It typically evaluates to an `Error`, although technically JavaScript does not require that thrown values are `Error`s. ### release ```json ["release", importId, refcount] ``` Instructs the recipient to release the given entry in the import table, disposing whatever it is connected to. If the import is a promise, the recipient is no longer obliged to send a resolve message for it, though it is still permitted to do so. `refcount` is the total number of times this import ID has been "introduced": the number of times it has been the subject of an `export` or `promise` expression, plus 1 if it was created by a push. The refcount must be sent to avoid a race condition if the receiving side has recently exported the same ID again. The exporter remembers how many times it has exported this ID, decrements by the refcount of any release messages received, and only actually releases the ID when the count reaches zero. ### stream ```json ["stream", expression] ``` Like push, asks the recipient to evaluate the given expression, and the expression is implicitly assigned the next sequential positive import ID. However, unlike push: - Promise pipelining on the result is **not** supported. The caller must not refer to the import ID in subsequent expressions. - The expression is automatically considered pulled. No separate pull message is needed. - Once the recipient sends a resolve or reject for the result, the export is implicitly released with a refcount of 1. No separate release message is needed. This message type is designed for streaming writes, where the result is expected to be empty and the overhead of separate pull and release messages is high. ### pipe ```json ["pipe"] ``` Creates a "pipe" on the remote end. A pipe consists of a `ReadableStream` end and a `WritableStream` end. The pipe is implicitly assigned the next sequential positive import ID, similar to push. The new import is **not** a promise. It is immediately usable as if it were a `WritableStream`; the sender can call `write`, `close`, and/or `abort` on it, using the same interface described for the [`writable`](#writable) expression. The readable end of the pipe can be referenced in a subsequent message using the [`readable`](#readable) expression. That expression can only be used once per pipe. The purpose of the pipe mechanism is to support sending `ReadableStream` over RPC. When a message contains a `ReadableStream`, the sender first sends a `["pipe"]` message to establish the writable end, then begins pumping the stream's data through it, and includes the readable end in the subsequent message via `["readable", importId]`. This allows data to start flowing immediately without waiting for a network round trip. ### abort ```json ["abort", expression] ``` Indicates that the sender has experienced an error causing it to terminate the session. The expression evaluates to the error which caused the abort. No further messages will be sent nor received. ## Expressions Expressions are JSON-serializable object trees. All JSON types except arrays are interpreted literally. Arrays are further evaluated into a final value as follows. ### array ```json [[...]] ``` An array expression. The inner array contains expressions, one for each array element, which are individually evaluated to produce the final array value. For example, this expression represents an object containing an array: ```json { "key": [[ "abc", ["date", 1757214689123], [[0]] ]] } ``` - The 1st item in the array expression is an expression for the string `"abc"`. - The 2nd item is an expression for a date object. - The 3rd item is another array expression containing an integer expression representing zero. It evaluates to: ```js { key: [ "abc", Date(1757214689123), [0] ] } ``` ### undefined ```json ["undefined"] ``` The literal value `undefined`. ### inf, -inf, nan ```json ["inf"], ["-inf"], ["nan"] ``` The values `Infinity`, `-Infinity`, and `NaN`. ### bytes ```json ["bytes", base64] ["bytes", base64, type] ``` A byte container, represented as a base64-encoded string. If `type` is omitted, the receiver should deserialize bytes as its default `Uint8Array` for backwards compatibility. Otherwise, `type` preserves the byte container type across the wire. Supported `type` values: `ArrayBuffer`, `DataView`, `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array`, `Float32Array`, `Float64Array`. Multi-byte typed array elements are encoded in **little-endian** byte order. ### blob ```json ["blob", type, readableExpression] ``` A `Blob` value. `type` is the MIME type string (`blob.type`), which may be an empty string. `readableExpression` evaluates to a `ReadableStream` carrying the blob's bytes; in practice the encoder always uses a [`readable`](#readable) expression backed by a pipe. Because reading a `Blob`'s bytes is inherently asynchronous, the pipe path is always used. There is no inline fast path even for small blobs. The receiver must collect all chunks from the stream before delivering the value to application code. ### bigint ```json ["bigint", decimal] ``` A `bigint` value, represented as a decimal string. Receivers cap the maximum length of this string to bound parsing cost. ### date ```json ["date", number] ``` A JavaScript `Date` value. The number is milliseconds since the Unix epoch. ### set ```json ["set", elements] ``` A JavaScript `Set` value. `elements` is an array of expressions for the set elements. An element must not evaluate directly to a promise or `Blob`. Stubs are valid elements, and promises and `Blob`s may appear nested within another element. ### regexp ```json ["regexp", source, flags?] ``` A JavaScript `RegExp` value. `source` and `flags` are the strings from the regular expression's `source` and `flags` properties. The receiver reconstructs the value via `new RegExp(source, flags)`. `flags` is omitted when the expression has no flags. For example: ```json ["regexp", "foo\\d+", "gi"] ["regexp", "^bar$"] ``` ### error ```json ["error", type, message, stack?, props?] ``` A JavaScript `Error` value. `type` is the name of the specific well-known `Error` subclass, e.g. `"TypeError"`. `message` is the error message. `stack` may optionally contain the stack trace, though **by default stacks are redacted for security reasons**. `props` is an optional fifth element carrying any extra data attached to the error. It is a JSON object whose keys are the error's own enumerable properties (plus the standard non-enumerable `cause` slot, and `errors` for `AggregateError`), and whose values are themselves valid expressions of this protocol, so they round-trip naturally. Property values that cannot be represented are silently dropped from `props`; the error itself always reaches the receiver. When `props` is present, `stack` is normalised to `null` if absent, so that positional indexing for `props` is unambiguous. When there are no extras, the legacy 3- or 4-element form is emitted unchanged. ### url ```json ["url", href] ``` A `URL` object. `href` is the fully-serialized, normalized URL string, the value of the URL's `href` property. The receiver reconstructs it with `new URL(href)`. For example: ```json ["url", "https://example.com/path?q=1"] ``` ### headers ```json ["headers", pairs] ``` A `Headers` object from the Fetch API. `pairs` is an array of `[name, value]` pairs, where both are strings. For example: ```json ["headers", [["content-type", "text/plain"], ["x-custom", "hello"]]] ``` ### request ```json ["request", url, init] ``` A `Request` object from the Fetch API. `url` and `init` are the parameters to pass to `Request`'s constructor. The sender should omit properties from `init` when their value would be the default anyway. `init.headers`, if present, must contain an array of pairs suitable to pass to the `Headers` constructor. `init.body`, if present, is an expression for the body, which must evaluate to `null`, a string, `Uint8Array`, or `ReadableStream`. Other properties of `init` must be plain values; they are not evaluated as expressions before being passed to the constructor. At this time, `init.signal` is not supported and must not be sent, though that will change when `AbortSignal` gains support for serialization. ### response ```json ["response", body, init] ``` A `Response` object from the Fetch API. `body` and `init` are the parameters to pass to `Response`'s constructor. `body` is an expression which must evaluate to `null`, a string, `Uint8Array`, or `ReadableStream`. `init.headers`, if present, must contain an array of pairs suitable for the `Headers` constructor. Other properties of `init` must be plain values. At this time, `init.webSocket` (a Cloudflare Workers extension) is not supported and must not be sent, though that may change if `WebSocket` gains support for serialization. ### import / pipeline ```json ["import", importId, propertyPath, callArguments] ["pipeline", importId, propertyPath, callArguments] ``` References an entry on the import table, from the perspective of the sender, possibly performing actions on it. If the type is `import`, the expression evaluates to a **stub**. If it is `pipeline`, the expression evaluates to a **promise**. The difference is important because promises must be replaced with their resolution before delivering the message to the application, whereas stubs are delivered as stubs without waiting for any resolution. `propertyPath` is optional. If specified, it is an array of property names (strings or numbers) leading to a specific property of the import's target. The expression evaluates to that property, unless `callArguments` is also specified. `callArguments` is also optional. If specified, the given property is called as a function. `callArguments` is an array of expressions, evaluated to produce the arguments to the call. ### remap ```json ["remap", importId, propertyPath, captures, instructions] ``` Implements the [`.map()`](/concepts/map/) operation. We call it "remap" so as not to confuse it with the serialization of a `Map` object. `importId` and `propertyPath` are the same as for `import`; they identify the particular property to be mapped. `captures` and `instructions` define the mapper function to apply to the target value. `captures` defines the set of stubs which the mapper function has captured, in the sense of a lambda capture. The body of the function may call these stubs. The format is an array where each member is either `["import", importId]` or `["export", exportId]`, referring to an entry on the sender's import or export table respectively. `instructions` contains a list of expressions to evaluate in order to execute the mapper on a particular input value. Each instruction is an expression in the same format described here, but with special handling of imports and exports. For the purpose of mapper instructions, **there is no export table**, and the import table is defined as follows: | Index | Refers to | | -------- | ---------------------------------------------------------------- | | Negative | The `captures` list, starting from -1 (`-1` is `captures[0]`). | | Zero | The input value of the map function. | | Positive | The result of a previous instruction (`1` is `instructions[0]`). | The instructions are always evaluated in order. Each instruction may only import results of instructions that came before it. The last instruction evaluates to the return value of the map function. ### export ```json ["export", exportId] ``` The sender is exporting a new stub, or re-exporting a stub that was exported before. The expression evaluates to a stub. ### promise ```json ["promise", exportId] ``` Like `export`, but the expression evaluates to a promise. Promises must be replaced with their resolution before the message is finally delivered to the application. The `exportId` in this case is always a newly-allocated ID. The sender will proactively send a resolve or reject message for this ID when the promise resolves, unless it is released first. The recipient does not need to pull the promise explicitly; it is assumed the recipient always wants the resolution. ### writable ```json ["writable", exportId] ``` Represents a `WritableStream`. The sender has called `getWriter()` on the stream, locking it, and holds the writer to handle incoming operations. The `exportId` refers to an export table entry that accepts the following method calls: | Method | Meaning | | ---------------- | --------------------------------------------------------- | | `write(chunk)` | Write a chunk. The chunk can be any RPC-compatible value. | | `close()` | Close the stream normally; all data has been written. | | `abort(reason?)` | Abort the stream with an optional reason. | These correspond to the methods of `WritableStreamDefaultWriter`. If the export is released without `close()` having been called, the sender aborts the stream, indicating abnormal termination such as a network disconnect. The receiver does not need to wait for each `write()` call to complete before sending the next one, nor before sending `close()`. The sender processes writes in order. The receiver should wait for `close()` to complete to verify that all writes were successful; if any write failed, `close()` also fails with that error. ### readable ```json ["readable", importId] ``` References the readable end of a pipe previously created by a [`pipe`](#pipe) message. `importId` must refer to an import table entry that was created as a pipe. The expression evaluates to a `ReadableStream`. This expression can only be used **once per pipe**. Once the readable end has been retrieved, it is removed from the pipe entry. # Bun > Serve Cap'n Web from Bun.serve using newBunWebSocketRpcHandler. Source: https://capnweb.com/servers/bun/ · Markdown: https://capnweb.com/servers/bun/index.md Bun's server-side WebSocket API uses [callback-based handlers](https://bun.sh/docs/runtime/http/websockets) instead of the standard `addEventListener` interface. Cap'n Web provides `newBunWebSocketRpcHandler()`, which returns a handler object you can pass directly to `Bun.serve()`. ```ts import { RpcTarget, newBunWebSocketRpcHandler, newHttpBatchRpcResponse } from 'capnweb'; class MyApiImpl extends RpcTarget implements MyApi { // ... define API, same as above ... } // Create a WebSocket handler that manages RPC sessions automatically. // The callback is invoked once per connection to create a fresh API instance. let rpcHandler = newBunWebSocketRpcHandler(() => new MyApiImpl()); Bun.serve({ async fetch(req, server) { let url = new URL(req.url); if (url.pathname === '/api') { // Upgrade WebSocket requests. if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') { if (server.upgrade(req)) return; return new Response('WebSocket upgrade failed', { status: 500 }); } // Handle HTTP batch requests. let response = await newHttpBatchRpcResponse(req, new MyApiImpl()); response.headers.set('Access-Control-Allow-Origin', '*'); return response; } return new Response('Not Found', { status: 404 }); }, // Pass the handler directly -- no manual wiring needed. websocket: rpcHandler, }); ``` Note that the callback passed to `newBunWebSocketRpcHandler()` runs **once per connection**, so each client gets its own API instance. That is usually what you want: per-connection state such as authentication lives naturally on that instance. ## Payload limits Bun's `Bun.serve()` accepts `maxPayloadLength` in its `websocket` options. Set it when exposed to untrusted peers. See [Security considerations](/guides/security/). # Deno > Serve Cap'n Web from Deno.serve, handling both HTTP batch and WebSocket upgrades. Source: https://capnweb.com/servers/deno/ · Markdown: https://capnweb.com/servers/deno/index.md Import the package with the `npm:` specifier and use the standard Fetch-API helpers. ```ts import { newHttpBatchRpcResponse, newWebSocketRpcSession, RpcTarget, } from 'npm:capnweb'; // This is the server implementation. class MyApiImpl extends RpcTarget implements MyApi { // ... define API, same as above ... } Deno.serve(async (req) => { const url = new URL(req.url); if (url.pathname === '/api') { if (req.headers.get('upgrade') === 'websocket') { const { socket, response } = Deno.upgradeWebSocket(req); socket.addEventListener('open', () => { newWebSocketRpcSession(socket, new MyApiImpl()); }); return response; } else { const response = await newHttpBatchRpcResponse(req, new MyApiImpl()); // If you are accepting WebSockets, then you might as well accept // cross-origin HTTP, since WebSockets always permit cross-origin requests // anyway. But see security considerations for further discussion. response.headers.set('Access-Control-Allow-Origin', '*'); return response; } } return new Response('Not Found', { status: 404 }); }); ``` :::note Start the RPC session from the `open` event, not immediately after `upgradeWebSocket()`. The socket is not ready to send until then. ::: Run it with network permission: ```sh deno run --allow-net server.ts ``` # Hono > Use the @hono/capnweb middleware to mount a Cap'n Web endpoint in a Hono app. Source: https://capnweb.com/servers/hono/ · Markdown: https://capnweb.com/servers/hono/index.md If your app is built on [Hono](https://hono.dev/), on any runtime it supports, check out [`@hono/capnweb`](https://github.com/honojs/middleware/tree/main/packages/capnweb). ```sh npm i @hono/capnweb ``` The middleware mounts a Cap'n Web endpoint on a route in your existing Hono app, so your RPC API can live alongside your regular HTTP routes and share the same middleware stack for logging, CORS, and so on. Refer to the [`@hono/capnweb` README](https://github.com/honojs/middleware/tree/main/packages/capnweb) for current usage and options; it is maintained in the Hono middleware repository, not here. ## Rolling your own If you'd rather not add a dependency, Hono handlers receive standard `Request` objects and return standard `Response` objects, so the generic Fetch-API helpers work directly: ```ts import { Hono } from 'hono'; import { RpcTarget, newHttpBatchRpcResponse } from 'capnweb'; class MyApiImpl extends RpcTarget { greet(name: string) { return `Hello, ${name}!`; } } const app = new Hono(); app.post('/api', (c) => newHttpBatchRpcResponse(c.req.raw, new MyApiImpl())); export default app; ``` WebSocket support depends on the runtime you deploy Hono to. See [Cloudflare Workers](/servers/workers/), [Node.js](/servers/node/), [Deno](/servers/deno/), or [Bun](/servers/bun/). # Node.js > Serve Cap'n Web from Node's http module, including WebSocket support via the ws package. Source: https://capnweb.com/servers/node/ · Markdown: https://capnweb.com/servers/node/index.md A server on Node.js is a bit more involved, due to the awkward handling of WebSockets in Node's HTTP library. ```ts import http from 'node:http'; import { WebSocketServer } from 'ws'; // npm package import { RpcTarget, newWebSocketRpcSession, nodeHttpBatchRpcResponse } from 'capnweb'; class MyApiImpl extends RpcTarget implements MyApi { // ... define API, same as above ... } // Run standard HTTP server on a port. let httpServer = http.createServer(async (request, response) => { if (request.headers.upgrade?.toLowerCase() === 'websocket') { // Ignore, should be handled by WebSocketServer instead. return; } // Accept Cap'n Web requests at `/api`. if (request.url === '/api') { try { await nodeHttpBatchRpcResponse(request, response, new MyApiImpl(), { // If you are accepting WebSockets, then you might as well accept // cross-origin HTTP, since WebSockets always permit cross-origin // requests anyway. But see security considerations for discussion. headers: { 'Access-Control-Allow-Origin': '*' }, }); } catch (err) { response.writeHead(500, { 'content-type': 'text/plain' }); response.end(String(err?.stack || err)); } return; } response.writeHead(404, { 'content-type': 'text/plain' }); response.end('Not Found'); }); // Arrange to handle WebSockets as well, using the `ws` package. You can skip // this if you only want to handle HTTP batch requests. let wsServer = new WebSocketServer({ server: httpServer }); wsServer.on('connection', (ws) => { // The `as any` here is because the `ws` module seems to have its own // `WebSocket` type declaration that's incompatible with the standard one. In // practice, though, they are compatible enough for Cap'n Web! newWebSocketRpcSession(ws as any, new MyApiImpl()); }); // Accept requests on port 8080. httpServer.listen(8080); ``` ## Install the WebSocket dependency You only need `ws` if you want to accept WebSocket sessions. HTTP batch works with nothing but `node:http`. ```sh npm i ws npm i -D @types/ws ``` ## Payload limits `ws` supports a `maxPayload` option, and you should set it if you are exposed to untrusted peers: ```ts let wsServer = new WebSocketServer({ server: httpServer, maxPayload: 1024 * 1024, // 1 MiB }); ``` Cap'n Web's own message-size check runs *after* the transport has returned a complete message, so transport-level limits are the first line of defence. See [Security considerations](/guides/security/). # Other Runtimes > The two portable functions that let you serve Cap'n Web from any modern JavaScript runtime. Source: https://capnweb.com/servers/other/ · Markdown: https://capnweb.com/servers/other/index.md Every runtime does HTTP handling and WebSockets a little differently, although most modern runtimes use the standard `Request` and `Response` types from the Fetch API, as well as the standard `WebSocket` API. You should be able to use these two functions, exported by `capnweb`, to implement both HTTP batch and WebSocket handling on all platforms: ```ts // Run a single HTTP batch. function newHttpBatchRpcResponse( request: Request, yourApi: RpcTarget, options?: RpcSessionOptions ): Promise; // Run a WebSocket session. // // This is actually the same function as is used on the client side! But on the // server, you should pass in a `WebSocket` object representing the already-open // connection, instead of a URL string, and you pass your API implementation as // the second parameter. // // You can dispose the returned `Disposable` to close the connection, or just // let it run until the client closes it. function newWebSocketRpcSession( webSocket: WebSocket, yourApi: RpcTarget, options?: RpcSessionOptions ): Disposable; ``` ## The general shape Both transports hang off one request handler. Check the path, then decide between a WebSocket upgrade and a batch: ```ts async function handle(request: Request): Promise { let url = new URL(request.url); if (url.pathname !== '/api') { return new Response('Not Found', { status: 404 }); } if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { // Runtime-specific: obtain a WebSocket for this request, then: // newWebSocketRpcSession(socket, new MyApiImpl()); // ...and return whatever response the runtime expects for an upgrade. } return newHttpBatchRpcResponse(request, new MyApiImpl()); } ``` The only genuinely runtime-specific part is obtaining the `WebSocket` object for an upgrade request. Everything else is portable. ## If your runtime isn't HTTP at all Cap'n Web only needs a bidirectional stream of discrete messages. If you have one (a TCP socket, a message queue, a serial link, an `ipc` channel between processes), implement [`RpcTransport`](/transports/custom/) and use `new RpcSession(transport, localMain)` directly. # Cloudflare Workers > Serve Cap'n Web from a Worker with newWorkersRpcResponse, handling HTTP batch and WebSocket at once. Source: https://capnweb.com/servers/workers/ · Markdown: https://capnweb.com/servers/workers/index.md The helper function `newWorkersRpcResponse()` makes it easy to implement an HTTP server that accepts both the HTTP batch and WebSocket APIs at once. ```ts import { RpcTarget, newWorkersRpcResponse } from 'capnweb'; // Define our server implementation. class MyApiImpl extends RpcTarget implements MyApi { constructor(private userInfo: UserInfo) {} getUserInfo(): UserInfo { return this.userInfo; } greet(name: string): string { return `Hello, ${name}!`; } } // Define our Worker HTTP handler. export default { fetch(request: Request, env, ctx) { let userInfo: UserInfo = authenticateFromCookie(request); let url = new URL(request.url); // Serve API at `/api`. if (url.pathname === '/api') { return newWorkersRpcResponse(request, new MyApiImpl(userInfo)); } return new Response('Not found', { status: 404 }); }, }; ``` That single call handles content negotiation: a normal POST is treated as an [HTTP batch](/transports/http-batch/), and an upgrade request becomes a [WebSocket session](/transports/websocket/). :::caution Authenticating from a cookie works for HTTP batch, but browsers do not send custom headers on WebSocket connections and always allow cross-site WebSocket connections. For anything reachable by WebSocket, authenticate in-band instead. See [Security considerations](/guides/security/). ::: ## Compatibility with Workers' built-in RPC Cloudflare Workers has long featured [a built-in RPC system with semantics similar to Cap'n Web](https://developers.cloudflare.com/workers/runtime-apis/rpc/). Cap'n Web is designed to be compatible with it: you can pass Cap'n Web RPC stubs over Workers RPC and vice versa, and the system automatically wraps one stub type in the other and arranges to proxy calls. For best compatibility, set your [compatibility date](https://developers.cloudflare.com/workers/configuration/compatibility-dates/) to at least `2026-01-20`, or enable the [compatibility flag](https://developers.cloudflare.com/workers/configuration/compatibility-flags/) `rpc_params_dup_stubs`. ```jsonc // wrangler.jsonc { "name": "my-api", "main": "src/index.ts", "compatibility_date": "2026-01-20", // Or, until that date is reachable: // "compatibility_flags": ["rpc_params_dup_stubs"] } ``` See [Workers RPC interop](/guides/workers-rpc/) for the full feature comparison. ## CPU limits Pipelining lets a client enqueue a lot of work in one message. Consider configuring [per-request CPU limits](https://developers.cloudflare.com/workers/wrangler/configuration/#limits) lower than the default 30s. Note that in stateless Workers (that is, not Durable Objects), the system considers an entire WebSocket session to be one "request" for CPU limit purposes. ```jsonc // wrangler.jsonc { "limits": { "cpu_ms": 5000 } } ``` ## Durable Objects For stateful sessions such as chat rooms, collaborative documents, or anything where clients need to reach the *same* server object, route the WebSocket to a Durable Object and start the session there. The Durable Object's `fetch()` can call `newWorkersRpcResponse()` exactly the same way. # Installation > Install Cap'n Web from npm, and the TypeScript settings you need for `using` declarations. Source: https://capnweb.com/start/installation/ · Markdown: https://capnweb.com/start/installation/index.md Cap'n Web is [a single npm package](https://www.npmjs.com/package/capnweb) with no dependencies. ```sh npm i capnweb ``` There is no build step, no schema compiler, and no code generation. Import it and go: ```ts import { RpcTarget, RpcStub, newWebSocketRpcSession } from 'capnweb'; ``` ## Runtime support Cap'n Web works in all major browsers, Cloudflare Workers, Node.js, Bun, Deno, and other modern JavaScript runtimes. The package ships runtime-specific entry points and your bundler or runtime will pick the right one automatically: | Runtime | Notes | | ------------------ | ------------------------------------------------------------------------------------ | | Browsers | `fetch` and `WebSocket` are used directly. | | Cloudflare Workers | Uses the `workerd` export condition; `RpcTarget` aliases the built-in. | | Node.js | Use the [`ws`](https://www.npmjs.com/package/ws) package for server-side WebSockets. | | Deno | Import as `npm:capnweb`. | | Bun | Uses the `bun` export condition. | Beyond `fetch` or `WebSocket`, Cap'n Web's serializer inspects a handful of WHATWG globals to decide how to encode a value, and expects them to exist: `ReadableStream`, `WritableStream`, `Blob`, `URL`, `Headers`, `Request` and `Response`. All five runtimes above provide them. Other JavaScript environments may need help. [React Native](https://reactnative.dev/) is the usual example: it has `fetch`, `WebSocket`, `Blob` and `URL`, but no `ReadableStream` or `WritableStream`, so you will need a WHATWG streams polyfill loaded before `capnweb`. React Native is not covered by CI, so treat it as untested rather than unsupported; a CI contribution would be very welcome. If a runtime has no suitable network API at all, you can still use Cap'n Web by supplying a [custom transport](/transports/custom/) over any bidirectional message stream. ## TypeScript setup Cap'n Web is written in TypeScript and ships its own types; you do not need a `@types` package. Stubs integrate with JavaScript's [explicit resource management](https://v8.dev/features/explicit-resource-management), so many examples in these docs use `using` declarations. To compile `using`, your `tsconfig.json` needs a recent target and the matching libs: ```json { "compilerOptions": { "target": "esnext", "lib": ["esnext", "dom"], "module": "nodenext", "moduleResolution": "nodenext", "strict": true } } ``` `using` became widely available in JavaScript engines in mid-2025, and has been supported via transpilers and polyfills for a few years before that. If you cannot use it, every disposable value also has an explicit `[Symbol.dispose]()` method you can call yourself. See [Disposal](/concepts/disposal/). ## Optional: build-time validation Cap'n Web does not perform runtime type checking by default. The companion package [`capnweb-validate`](/guides/validation/) generates runtime validators from your TypeScript types at build time. ```sh npm i -D capnweb-validate ``` # Introduction > What Cap'n Web is, how it relates to Cap'n Proto, and why object-capability RPC makes it more expressive than most RPC systems. Source: https://capnweb.com/start/introduction/ · Markdown: https://capnweb.com/start/introduction/index.md Cap'n Web is a spiritual sibling to [Cap'n Proto](https://capnproto.org) (and is created by the same author), but designed to play nice in the web stack. That means: - Like Cap'n Proto, it is an **object-capability protocol**. ("Cap'n" is short for "capabilities and", making this *capabilities and the web*. The nautical breakfast-cereal overtones are inherited from Cap'n Proto, which bills itself as a "cerealization protocol", and are entirely deliberate.) Possession of a stub is itself the authority to use it, which is what [Security](/guides/security/) builds on. - Unlike Cap'n Proto, Cap'n Web has **no schemas**. In fact, it has almost no boilerplate whatsoever. This means it works more like the [JavaScript-native RPC system in Cloudflare Workers](https://blog.cloudflare.com/javascript-native-rpc/). - That said, it integrates nicely with TypeScript. - Also unlike Cap'n Proto, Cap'n Web's underlying serialization is **human-readable**. It's just JSON, with a little pre- and post-processing. - It works over HTTP, WebSocket, and `postMessage()` out of the box, and can be extended to other transports easily. - It works in all major browsers, Cloudflare Workers, Node.js, Bun, Deno, and other modern JavaScript runtimes. The whole thing compresses (minify + gzip) to **%BUNDLE_SIZE% with no dependencies**. ## Why object-capability RPC Cap'n Web is more expressive than almost every other RPC system, because it implements an object-capability RPC model. That means it: - **Supports bidirectional calling.** The client can call the server, and the server can also call the client. - **Supports passing functions by reference.** If you pass a function over RPC, the recipient receives a "stub". When they call the stub, they actually make an RPC back to you, invoking the function where it was created. This is how bidirectional calling happens: the client passes a callback to the server, and then the server can call it later. - **Supports passing objects by reference.** If a class extends the special marker type [`RpcTarget`](/concepts/rpc-target/), then instances of that class are passed by reference, with method calls calling back to the location where the object was created. - **Supports promise pipelining.** When you start an RPC, you get back a promise. Instead of awaiting it, you can immediately use the promise in dependent RPCs, thus performing a chain of calls in a single network round trip. - **Supports capability-based security patterns.** Holding a reference *is* the permission to use it, which makes authorization patterns fall out naturally. ## How it compares | | Cap'n Web | Cap'n Proto | | ------------------- | --------------------- | ------------------------ | | Schemas | None | `.capnp` schema language | | Codegen | None | Required | | Serialization | JSON (human-readable) | Binary, zero-copy | | Object capabilities | Yes | Yes | | Promise pipelining | Yes | Yes | | Primary home | The web stack | C++ and systems software | Cap'n Web is *not* a port of Cap'n Proto, and the two do not interoperate on the wire. They share a model, an author, and a sense of humour. For how Cap'n Web stacks up against tRPC, JSON-RPC, GraphQL and the older distributed-object systems, see [How it compares](/guides/comparisons/). ## A protocol, or a library? Both, and the two are worth keeping apart. The `capnweb` npm package is an implementation. The [wire protocol](/reference/protocol/) is a specification, and you can write your own peer against it. The protocol is JavaScript-flavoured to about the same extent JSON is (its value types are the JavaScript built-ins), but nothing in the framing or the expression language demands a JavaScript implementation. The *library*, on the other hand, is deliberately scoped to JavaScript and TypeScript. If your backend is written in something else, Cap'n Proto is the answer today; see [using Cap'n Web from other languages](/guides/comparisons/#vs-capn-proto-and-using-capn-web-from-other-languages). ## Where to next - [Installation](/start/installation/): one npm package, no build step. - [Quickstart](/start/quickstart/): a working client and server. - [Pipelining tour](/start/pipelining-tour/): the part that makes it fast. - [How it compares](/guides/comparisons/): against the alternatives, including the honest gaps. # Pipelining Tour > Chain dependent RPC calls into a single network round trip, including the record-replay trick behind .map(). Source: https://capnweb.com/start/pipelining-tour/ · Markdown: https://capnweb.com/start/pipelining-tour/index.md Pipelining is what lets a chain of dependent calls cost one round trip instead of one per call. The rest of the library is built around it. ## The problem A naive RPC client waits for each result before it can use it. Four dependent calls means four round trips: ```ts let authed = await api.authenticate(apiToken); // round trip 1 let userId = await authed.getUserId(); // round trip 2 let profile = await api.getUserProfile(userId); // round trip 3 let friends = await authed.getFriendIds(); // round trip 4 ``` On a 100 ms link, that's 400 ms of doing nothing. ## The trick Calling an RPC method returns an [`RpcPromise`](/concepts/promises/), not a regular `Promise`. An `RpcPromise` is *also a stub for its own eventual result*. So you can call methods on it, read properties of it, and pass it as an argument to other calls, all before it resolves. When the peer receives a call whose arguments contain an unresolved promise, it substitutes the resolved value before delivering the call to your application code. ```ts import { newHttpBatchRpcSession } from 'capnweb'; let api = newHttpBatchRpcSession('https://example.com/api'); // Call authenticate(), but don't await it. We can use the returned promise // to make "pipelined" calls without waiting. let authedApi: RpcPromise = api.authenticate(apiToken); // Make a pipelined call to get the user's ID. Again, don't await it. let userIdPromise: RpcPromise = authedApi.getUserId(); // Fetch the user's public profile, based on the user ID. Notice how we can use // `RpcPromise` anywhere a `T` is expected. The promise will be replaced with // its resolution before delivering the call. let profilePromise = api.getUserProfile(userIdPromise); // Another call to get the user's friends. let friendsPromise = authedApi.getFriendIds(); // That only returns an array of user IDs, but we want all the profile info too, // so use the magic .map() function to get them. Still one round trip. let friendProfilesPromise = friendsPromise.map((id: RpcPromise) => { return { id, profile: api.getUserProfile(id) }; }); // Now await. The batch is sent at this point. let [profile, friendProfiles] = await Promise.all([profilePromise, friendProfilesPromise]); console.log(`Hello, ${profile.name}!`); ``` Five logical calls, arbitrary depth of dependency, **one round trip**. :::note Await every promise whose result you actually want, and await them together. If you don't await a promise before the batch is sent, the system detects this and doesn't ask the server to send the return value back at all; it saves the bandwidth. ::: ## Properties pipeline too You don't only pipeline calls. You can pipeline into a *property* of a pending result: ```ts // In a single round trip, authenticate the user and fetch their public profile // given their ID. let user = api.authenticate(cookie); let profile = await api.getUserProfile(user.id); ``` ## How `.map()` can possibly work `friendsPromise.map(...)` applies your callback to a value that doesn't exist yet on the client, and it does so without sending any code over the wire. Cap'n Web does **not** ship arbitrary code. The trick is **record-replay**: 1. On the calling side, Cap'n Web invokes your callback once in a special *recording* mode, passing a placeholder stub that records what you do with it. 2. During that invocation, any RPCs the callback invokes (on *any* stub) are not executed, only recorded as actions the callback performs. Any stubs used are "captured" as well. 3. The recording plus the capture list is sent to the peer, where it can be replayed as needed for each individual result. Because every not-yet-determined value the callback sees is an `RpcPromise`, the callback's behaviour is deterministic. Real computation (arithmetic, branching) can't meaningfully consume those promises, so it must produce the same result on every invocation, and it gets performed once on the sending side, with the result baked into the recording. **Your JavaScript runs on the calling side exactly once; the RPCs it recorded run on the peer, once per element.** See [Which side runs what](/concepts/map/#which-side-runs-what) for the consequences, and [The magic `map()`](/concepts/map/) for the full rules and restrictions. ## With a WebSocket instead Pipelining is not exclusive to batches. On a long-lived [WebSocket session](/transports/websocket/) you get the same round-trip savings, but you're free to await whenever you like: ```ts using api = newWebSocketRpcSession('wss://example.com/api'); // Authenticate and get the user ID in one round trip. using authedApi: RpcPromise = api.authenticate(apiToken); let userId: number = await authedApi.getUserId(); // ... continue calling other methods, now or in the future ... ``` :::caution Pipelining makes it cheap for a malicious client to enqueue a *lot* of server work in one message. Rate-limit expensive operations. See [Security considerations](/guides/security/). ::: # Quickstart > Build a working Cap'n Web client and server, first in plain JavaScript and then with TypeScript types. Source: https://capnweb.com/start/quickstart/ · Markdown: https://capnweb.com/start/quickstart/index.md Let's build the smallest useful Cap'n Web service, then add types. ## A client Open a session and call a method on it: ```js import { newWebSocketRpcSession } from 'capnweb'; // One-line setup. let api = newWebSocketRpcSession('wss://example.com/api'); // Call a method on the server! let result = await api.hello('World'); console.log(result); ``` There is no client generation and no interface registration. `api` is a *stub*: a `Proxy` that appears to have every possible method. Calling one sends an RPC. ## A server The other half, implementing the `hello` the client just called: ```js import { RpcTarget, newWorkersRpcResponse } from 'capnweb'; // This is the server implementation. class MyApiServer extends RpcTarget { hello(name) { return `Hello, ${name}!`; } } // Standard Cloudflare Workers HTTP handler. // // (Node and other runtimes are supported too.) export default { fetch(request, env, ctx) { // Parse URL for routing. let url = new URL(request.url); // Serve API at `/api`. if (url.pathname === '/api') { return newWorkersRpcResponse(request, new MyApiServer()); } // You could serve other endpoints here... return new Response('Not found', { status: 404 }); }, }; ``` Extending [`RpcTarget`](/concepts/rpc-target/) is what makes the object available over RPC. Callers can invoke its prototype methods and getters, but not its instance properties. See [Server runtimes](/servers/workers/) for Node.js, Deno, Bun, and Hono equivalents. ## Adding types You don't *have to* declare your interface separately; the client could just use `import("./server").ApiServer` as the type. But a shared types file is often cleaner: ```ts // shared/api.ts interface PublicApi { // Authenticate the API token, and return the authenticated API. authenticate(apiToken: string): AuthedApi; // Get a given user's public profile info. (Doesn't require authentication.) getUserProfile(userId: string): Promise; } interface AuthedApi { getUserId(): number; // Get the user IDs of all the user's friends. getFriendIds(): number[]; } type UserProfile = { name: string; photoUrl: string; }; ``` On the server, implement the interface as an `RpcTarget`: ```ts import { newWorkersRpcResponse, RpcTarget } from 'capnweb'; class ApiServer extends RpcTarget implements PublicApi { // ... implement PublicApi ... } export default { async fetch(req, env, ctx) { // ... same as previous example ... }, }; ``` On the client, the stub is fully typed: you get compile-time checking and autocomplete, even though nothing was generated: ```ts import { newWebSocketRpcSession } from 'capnweb'; using api = newWebSocketRpcSession('wss://example.com/api'); using authed = api.authenticate(apiToken); let userId: number = await authed.getUserId(); ``` :::caution TypeScript types are erased at runtime. A malicious client can send values of types you did not expect. See [Security considerations](/guides/security/) and [Runtime validation](/guides/validation/). ::: ## Documenting your API There is no OpenAPI document to generate, because there is no schema to generate it from, and no separate artifact that can drift out of date with the implementation. The shared types file *is* the API description, so document it there: ```ts // shared/api.ts export interface AuthedApi { /** * The user IDs of everyone this user is friends with. * * Returns at most 5000 entries; there is currently no pagination. */ getFriendIds(): number[]; } ``` That gives you three things at once: hover documentation in every editor for anyone importing the file, a single file you can hand someone as "the API", and, if you want a browsable site, ordinary TypeScript documentation output from a tool like [TypeDoc](https://typedoc.org/). The catch is the one you already know from OpenAPI: comments are not enforced. If you want the boundary actually checked, that is [runtime validation](/guides/validation/). ## Which transport? | You want | Use | | -------------------------------------------- | ---------------------------------------- | | A burst of calls, then done | [HTTP batch](/transports/http-batch/) | | A long-lived session, server-initiated calls | [WebSocket](/transports/websocket/) | | Talk to a Web Worker or iframe | [MessagePort](/transports/message-port/) | | Something else entirely | [Custom transport](/transports/custom/) | ## Next steps - [Pipelining tour](/start/pipelining-tour/): do all of the above in one round trip. - [What can be passed](/concepts/values/): the type system on the wire. - [Disposal](/concepts/disposal/): the one piece of bookkeeping Cap'n Web asks of you. # Transports > Choosing between HTTP batch, WebSocket, MessagePort, and custom transports, and the session model they share. Source: https://capnweb.com/transports/ · Markdown: https://capnweb.com/transports/index.md Cap'n Web runs over any bidirectional stream of discrete messages. Four options ship in the box, and you can write your own. | Transport | Long-lived | Server can call client | Best for | | ---------------------------------------- | ---------- | ---------------------- | ---------------------------------------------- | | [HTTP batch](/transports/http-batch/) | No | No | A burst of calls, then done. Stateless edges. | | [WebSocket](/transports/websocket/) | Yes | Yes | Interactive apps, subscriptions, callbacks. | | [MessagePort](/transports/message-port/) | Yes | Yes | Web Workers, iframes, same-process boundaries. | | [Custom](/transports/custom/) | Up to you | Yes | Anything else with two directions. | ## Sessions are symmetric Sessions are entirely symmetric: **neither side is defined as the "client" nor the "server".** Each side can optionally expose a "main interface" to the other. In typical scenarios with a logical client and server, the server exposes a main interface and the client does not. The words "client" and "server" appear throughout these docs only as a convention to make explanations natural. "Client" generally means the caller of an RPC or the importer of a stub; "server" means the callee or exporter. ## Disposal ends the session Disposing the root stub of a session closes the connection: ```ts { using api = newWebSocketRpcSession('wss://example.com/api'); // ... use api ... } // connection closed here ``` Only the **root** stub behaves this way. Disposing any other stub releases the object it points at on the peer, but leaves the connection open: ```ts using api = newWebSocketRpcSession('wss://example.com/api'); { using authed = api.authenticate(apiToken); // ... } // AuthedApi released on the server; the session is still up. ``` For HTTP batch, the session ends when the batch completes, and all stubs are implicitly disposed at that point. See [Disposal](/concepts/disposal/). Session state is in-memory and lasts exactly as long as the session; there is nothing to persist and no session store to run. [Sessions & reconnection](/guides/sessions/) covers what that means for reconnecting, versioning and load balancing. ## Message framing The protocol operates on a bidirectional stream of discrete messages, each a single JSON value. The protocol itself does not define framing: that is the transport's job. - Transports with native framing (WebSocket, `MessagePort`) map one transport message to one RPC message. - The built-in HTTP transport is newline-delimited, packing a series of messages into a single request or response body. An empty body means zero messages. See the [wire protocol reference](/reference/protocol/) for the full picture. # Custom Transports > Implement RpcTransport to run Cap'n Web over any bidirectional stream, and tune how much encoding it does for you. Source: https://capnweb.com/transports/custom/ · Markdown: https://capnweb.com/transports/custom/index.md You can implement a custom RPC transport across any bidirectional stream. ## The interface A transport is two required methods, plus `abort()` if there is something useful to do with a fatal error: ```ts // Interface for an RPC transport, which is a simple bidirectional message stream. export interface RpcTransport { // Sends a message to the other end. send(message: string): Promise; // Receives a message sent by the other end. // // If and when the transport becomes disconnected, this will reject. The thrown // error will be propagated to all outstanding calls and future calls on any // stubs associated with the session. If there are no outstanding calls (and // none are made in the future), then the error does not propagate anywhere -- // this is considered a "clean" shutdown. receive(): Promise; // Indicates that the RPC system has suffered an error that prevents the session // from continuing. The transport should ideally try to send any queued messages // if it can, and then close the connection. (It's not strictly necessary to // deliver queued messages, but the last message sent before abort() is called is // often an "abort" message, which communicates the error to the peer, so if that // is dropped, the peer may have less information about what happened.) abort?(reason: any): void; } ``` ## Starting a session Hand the transport to `RpcSession`, along with whatever you want the other end to be able to call: ```ts // Create the transport. let transport: RpcTransport = new MyTransport(); // Create the main interface we will expose to the other end. let localMain: RpcTarget = new MyMainInterface(); // Start the session. let session = new RpcSession(transport, localMain); // Get a stub for the other end's main interface. let stub: RemoteMainInterface = session.getRemoteMain(); // Now we can call methods on the stub. ``` Sessions are entirely symmetric: neither side is defined as the "client" nor the "server". Each side can optionally expose a main interface to the other. In typical client/server scenarios, the server exposes a main interface and the client does not. ## Encoding levels By default, `send()` accepts a string and `receive()` returns a string, with Cap'n Web handling the encoding all the way to and from strings. Transports that want more control over serialization can declare an `encodingLevel` property: | `encodingLevel` | What the transport receives | Use when | | --------------------------- | -------------------------------------------------------- | ------------------------------------------------------ | | `"string"` *(default)* | Fully-serialized JSON strings. | HTTP batch and WebSocket use this. | | `"jsonCompatible"` | JavaScript value trees that are JSON-compatible. | You serialize to CBOR, MessagePack, etc. | | `"jsonCompatibleWithBytes"` | Same, but byte arrays stay as `Uint8Array`. | Your format has native binary; avoids base64 overhead. | | `"structuredClonable"` | Structured-clonable values, native types passed through. | `MessagePort` and similar. | Details: - **`"string"`**: full JSON round-trip. The transport deals in strings only; Cap'n Web handles all encoding and decoding. - **`"jsonCompatible"`**: the transport works with JavaScript value trees, but they must be JSON-compatible. Cap'n Web still encodes special types, but skips the final `JSON.stringify`. The transport is responsible for serialization. - **`"jsonCompatibleWithBytes"`**: like `"jsonCompatible"`, except byte arrays are left as `Uint8Array` instead of base64-encoded, avoiding the ~33% base64 size overhead and the encode/decode CPU cost. Handy with CBOR or MessagePack. - **`"structuredClonable"`**: messages are structured-clonable values. Cap'n Web passes through native structured-clone types where possible, while still handling RPC-specific values such as stubs. ## Framing is your job The protocol operates on a stream of **discrete messages**; it does not define how they are framed. If your underlying stream is byte-oriented (a TCP socket, a serial line), you must add framing using length prefixes or newline delimiting, as the built-in HTTP transport does. ## A worked example A minimal transport over a pair of async queues: ```ts class QueueTransport implements RpcTransport { #outgoing: (msg: string) => void; #incoming: string[] = []; #waiters: ((msg: string) => void)[] = []; constructor(outgoing: (msg: string) => void) { this.#outgoing = outgoing; } // Call this when the underlying stream delivers a message. deliver(message: string) { let waiter = this.#waiters.shift(); if (waiter) waiter(message); else this.#incoming.push(message); } async send(message: string) { this.#outgoing(message); } receive(): Promise { let queued = this.#incoming.shift(); if (queued !== undefined) return Promise.resolve(queued); return new Promise((resolve) => this.#waiters.push(resolve)); } abort(reason: any) { console.error('transport aborted', reason); } } ``` :::caution Apply payload size limits at the transport layer. Cap'n Web enforces a maximum incoming message size before `JSON.parse`, but that check runs only after `receive()` has returned a *complete* message string, so transport-level limits are the first line of defence against buffering very large frames. See [Security considerations](/guides/security/). ::: # HTTP Batch > Send a whole dependent call graph in one HTTP request using newHttpBatchRpcSession. Source: https://capnweb.com/transports/http-batch/ · Markdown: https://capnweb.com/transports/http-batch/index.md In HTTP batch mode, a batch of RPC calls is made in a single HTTP request, with the server returning a batch of results. **Cap'n Web has a magic trick:** the results of one call in the batch can be used in the parameters to later calls *in the same batch*, even though the entire batch is sent at once. If you take the promise returned by one call and use it in the parameters to another, the promise is replaced with its resolution before delivering it to the callee. This is [promise pipelining](/concepts/promises/). ## Client Declare the interface, then open a batch against it: ```ts import { RpcTarget, RpcStub, newHttpBatchRpcSession } from 'capnweb'; // Declare our RPC interface. interface MyApi extends RpcTarget { // Returns information about the logged-in user. getUserInfo(): UserInfo; // Returns a friendly greeting for a user with the given name. greet(name: string): string; } // Start a batch request using this interface. using stub: RpcStub = newHttpBatchRpcSession('https://example.com/api'); // The batch will be sent on the next I/O tick (i.e. using setTimeout(sendBatch, 0)). // You have until then to add calls to the batch. // // We can make any number of calls as part of the batch, as long as we store the // promises without awaiting them yet. let promise1 = stub.greet('Alice'); let promise2 = stub.greet('Bob'); // A promise returned by one call can be used in the input to another call. The // first call's result will be substituted into the second call's parameters on // the server side. If the first call returns an object, you can even specify a // property of the object to pass to the second call, as shown here. let userInfoPromise = stub.getUserInfo(); let promise3 = stub.greet(userInfoPromise.name); // Use Promise.all() to wait on all the promises at once. NOTE: You don't // necessarily have to use Promise.all(), but you must make sure you have // explicitly awaited (or called `.then()` on) all promises before the batch is // sent. The system will only ask the server to send back results for the // promises you explicitly await. In this example, we have not awaited // `userInfoPromise` -- we only used it as a parameter to another call -- so the // result will not actually be returned. let [greeting1, greeting2, greeting3] = await Promise.all([promise1, promise2, promise3]); console.log(greeting1); console.log(greeting2); console.log(greeting3); ``` ## When the batch is sent The batch is dispatched on the next I/O tick. Everything you queue synchronously ends up in the same request. The first `await` is your deadline. :::caution Once the batch completes, the `stub` and everything derived from it stops working. You must start a new batch for further calls. ::: ## Why you might prefer batch over WebSocket - **Stateless.** Works on any HTTP endpoint, including cached/edge deployments with no persistent connections. - **Cheap.** No connection to keep alive, no reconnection logic, no heartbeats. - **No disposal bookkeeping.** All stubs are implicitly disposed when the batch ends. In exchange, the server cannot call you back later, and there is no subscription model. ## Server side Any of the [server runtimes](/servers/workers/) can answer a batch request: - Cloudflare Workers: `newWorkersRpcResponse()` handles batch *and* WebSocket. - Fetch-API runtimes: `newHttpBatchRpcResponse(request, api, options?)`. - Node.js: `nodeHttpBatchRpcResponse(request, response, api, options?)`. ## Cross-origin Batch requests are subject to normal CORS rules. If you also accept WebSockets, you might as well accept cross-origin HTTP, since WebSockets always permit cross-origin requests anyway: ```ts response.headers.set('Access-Control-Allow-Origin', '*'); ``` Read [Security considerations](/guides/security/) before doing this; in particular, do not rely on cookies for authentication. # MessagePort > Use Cap'n Web to talk to Web Workers, iframes, and other same-process contexts. Source: https://capnweb.com/transports/message-port/ · Markdown: https://capnweb.com/transports/message-port/index.md Cap'n Web can talk over `MessagePort`s. In a browser, this lets you use the same RPC model to talk to Web Workers, iframes, and other contexts: no serialization boilerplate, no ad-hoc message protocols with `type` fields and switch statements. ```ts import { RpcTarget, RpcStub, newMessagePortRpcSession } from 'capnweb'; // Declare our RPC interface. class Greeter extends RpcTarget { greet(name: string): string { return `Hello, ${name}!`; } } // Create a MessageChannel (pair of MessagePorts). let channel = new MessageChannel(); // Initialize the server on port1. newMessagePortRpcSession(channel.port1, new Greeter()); // Initialize the client on port2. using stub: RpcStub = newMessagePortRpcSession(channel.port2); // Now you can make calls. console.log(await stub.greet('Alice')); console.log(await stub.greet('Bob')); ``` ## Sending a port somewhere else In a real-world scenario you'd send one of the two ports to another context. A `MessagePort` can itself be transferred using `postMessage()`: `window.postMessage()`, `worker.postMessage()`, or even `port.postMessage()` on some other existing `MessagePort`. ```ts // Main thread let worker = new Worker('./worker.js', { type: 'module' }); let channel = new MessageChannel(); // Hand one end to the worker. worker.postMessage({ rpcPort: channel.port2 }, [channel.port2]); // Keep the other end and start talking. using api = newMessagePortRpcSession(channel.port1); console.log(await api.crunchNumbers([1, 2, 3])); ``` ```ts // worker.js import { RpcTarget, newMessagePortRpcSession } from 'capnweb'; class WorkerApi extends RpcTarget { crunchNumbers(values: number[]) { return values.reduce((a, b) => a + b, 0); } } self.addEventListener('message', (event) => { if (event.data?.rpcPort) { newMessagePortRpcSession(event.data.rpcPort, new WorkerApi()); } }); ``` :::danger Do not use a `Window` object itself as a port for RPC. Always create a new `MessageChannel` and send one of the ports over. Anyone can `postMessage()` to a window, and the RPC system does not authenticate that messages came from the expected sender. Verify that you received the *port itself* from the expected sender first, then let the RPC system take over. ::: ## Structured clone A `MessagePort` transport can avoid JSON entirely. Custom transports may declare `encodingLevel: "structuredClonable"` so that messages stay as structured-clonable values, passing through native types where possible while still handling RPC-specific values such as stubs. See [Custom transports](/transports/custom/#encoding-levels). # WebSocket > Long-lived, fully bidirectional Cap'n Web sessions with newWebSocketRpcSession. Source: https://capnweb.com/transports/websocket/ · Markdown: https://capnweb.com/transports/websocket/index.md In WebSocket mode, the client forms a long-lived connection to the server and makes many calls over it. The server can also make asynchronous calls **back to the client**. ## Client Declare the interface, then open a session against it: ```ts import { RpcTarget, RpcStub, newWebSocketRpcSession } from 'capnweb'; // Declare our RPC interface. interface MyApi extends RpcTarget { // Returns information about the logged-in user. getUserInfo(): UserInfo; // Returns a friendly greeting for a user with the given name. greet(name: string): string; } // Start a WebSocket session. // // (Note that disposing the root stub will close the connection. Here we declare // it with `using` so that the connection will be closed when the stub goes out // of scope, but you can also call `stub[Symbol.dispose]()` directly.) using stub: RpcStub = newWebSocketRpcSession('wss://example.com/api'); // With a WebSocket, we can freely make calls over time. console.log(await stub.greet('Alice')); console.log(await stub.greet('Bob')); // But we can still use Promise Pipelining to reduce round trips. Note that we // should use `using` with promises we don't intend to await so that the system // knows when we don't need them anymore. { using userInfoPromise = stub.getUserInfo(); console.log(await stub.greet(userInfoPromise.name)); } // Since we never awaited `userInfoPromise`, the server won't even bother // sending the response back over the wire. ``` ## Server calling the client Pass a callback and the server can invoke it whenever it likes: ```ts // Client await api.subscribe((event) => { console.log('server pushed:', event); }); ``` ```ts // Server class Api extends RpcTarget { #subscribers: RpcStub<(e: unknown) => void>[] = []; subscribe(cb: RpcStub<(e: unknown) => void>) { // Stubs in params are disposed when the call returns -- dup() to keep it. this.#subscribers.push(cb.dup()); } } ``` The `.dup()` there is mandatory. See [holding on to a callback](/concepts/disposal/#holding-on-to-a-callback-past-the-call-that-delivered-it). ## Server side `newWebSocketRpcSession()` is the *same function* used on the client. On the server, pass a `WebSocket` object representing the already-open connection, and your API implementation as the second parameter: ```ts function newWebSocketRpcSession( webSocket: WebSocket, yourApi: RpcTarget, options?: RpcSessionOptions ): Disposable; ``` Dispose the returned `Disposable` to close the connection, or let it run until the client closes it. Runtime-specific wiring: - [Cloudflare Workers](/servers/workers/): `newWorkersRpcResponse()` does it for you. - [Node.js](/servers/node/): use the `ws` package. - [Deno](/servers/deno/): `Deno.upgradeWebSocket()`. - [Bun](/servers/bun/): `newBunWebSocketRpcHandler()`. ## Disconnection A dropped connection breaks every stub associated with the session. Detect it with: ```ts stub.onRpcBroken((error) => { console.error('connection lost:', error); // tear down UI state, schedule a reconnect, ... }); ``` Cap'n Web does not reconnect automatically. Reconnection means establishing a new session and re-acquiring any capabilities you held, since stubs from the old session are permanently broken. See [Sessions & reconnection](/guides/sessions/) for the patterns that make this manageable, including the React one and how to resume a subscription without gaps. :::danger The WebSocket API in browsers always permits cross-site connections, and does not permit setting headers. Because of this, you generally **cannot use cookies or other headers for authentication.** Instead, authenticate in-band via an RPC method that returns the authenticated API. See [Security considerations](/guides/security/). :::