Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/http-batch-custom-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"capnweb": minor
---

`newHttpBatchRpcSession()` now accepts an optional `fetch` function in its options, used instead
of the global `fetch()` to send the batch. This makes it possible to send batches through a VPC or
service binding without overriding `globalThis.fetch`.
32 changes: 31 additions & 1 deletion __tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Licensed under the MIT license found in the LICENSE.txt file or at:
// https://opensource.org/license/mit

import { expect, it, describe, inject } from "vitest"
import { expect, it, describe, inject, vi } from "vitest"
import { deserialize, serialize, RpcSession, type RpcSessionOptions, RpcTransport,
type RpcTransportWithCustomEncoding, RpcTarget, RpcStub, RpcPromise, newWebSocketRpcSession,
newMessagePortRpcSession,
Expand Down Expand Up @@ -3316,6 +3316,36 @@ describe("HTTP requests", () => {
.toStrictEqual([36, 5, 9]);
});

it("sends the batch using a custom fetch function from options", async () => {

@ndisidore ndisidore Nov 22, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these only wrap global fetch, the binding path isnt covered. workerd.test.ts already has env.testServer (~L461) so a test there would be cheap

let url = `http://${inject("testServerHost")}`;
let calls: { input: string | Request, init?: RequestInit }[] = [];
let customFetch = (input: string | Request, init?: RequestInit) => {
calls.push({ input, init });
return fetch(input, init);
};

let cap = newHttpBatchRpcSession<TestTarget>(url, { fetch: customFetch });
let promise1 = cap.square(6);
let promise2 = cap.square(7);
expect(await Promise.all([promise1, promise2])).toStrictEqual([36, 49]);

expect(calls.length).toBe(1);
expect(calls[0].input).toBe(url);
expect(calls[0].init?.method).toBe("POST");
});

it("uses the global fetch when no custom fetch is given", async () => {
let url = `http://${inject("testServerHost")}`;
let spy = vi.spyOn(globalThis, "fetch");
try {
let cap = newHttpBatchRpcSession<TestTarget>(url);
expect(await cap.square(5)).toBe(25);
expect(spy.mock.calls.filter(c => c[0] === url).length).toBe(1);
} finally {
spy.mockRestore();
}
});

it("rejects non-POST requests with 405", async () => {
let response = await fetch(`http://${inject("testServerHost")}`, { method: "GET" });
expect(response.status).toBe(405);
Expand Down
15 changes: 15 additions & 0 deletions __tests__/workerd.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,4 +471,19 @@ describe("workerd RPC server", () => {
expect(await Promise.all([promise1, promise2, promise3]))
.toStrictEqual([36, 5, 9]);
})

it("can send an HTTP batch through a custom fetch function", async () => {
let calls = 0;
let cap = newHttpBatchRpcSession<TestTarget>("http://foo", {
fetch: (input, init) => {
++calls;
return (<Env>env).testServer.fetch(input, init);
},
});

let promise1 = cap.square(6);
let promise2 = cap.square(7);
expect(await Promise.all([promise1, promise2])).toStrictEqual([36, 49]);
expect(calls).toBe(1);
})
});
3 changes: 3 additions & 0 deletions packages/docs/src/content/docs/reference/api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ interface RpcTransport {
Passed as the last argument to the session and response helpers. Commonly used for response
`headers` (e.g. CORS) on the HTTP batch helpers.

`newHttpBatchRpcSession()` also accepts a `fetch` option (`HttpBatchRpcSessionOptions`), used
instead of the global `fetch()` to send the batch. [Docs](/transports/http-batch/#custom-fetch)

## Disposal at a glance

| You have | You must |
Expand Down
12 changes: 12 additions & 0 deletions packages/docs/src/content/docs/transports/http-batch.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,18 @@ console.log(greeting2);
console.log(greeting3);
```

### Custom `fetch`

By default the batch is sent with the global `fetch()`. To use a different function, such as a
VPC or service binding on Cloudflare Workers, pass it as the `fetch` option. It is called unbound,
so wrap a method that needs its receiver:

```ts
using stub = newHttpBatchRpcSession<MyApi>('https://example.com/api', {
fetch: (input, init) => env.VPC.fetch(input, init),
});
```

## When the batch is sent

The batch is dispatched on the next I/O tick. Everything you queue synchronously ends up in the same
Expand Down
19 changes: 17 additions & 2 deletions src/batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,25 @@ class BatchClientTransport implements RpcTransport {
}
}

export type HttpBatchRpcSessionOptions = RpcSessionOptions & {
/**
* Function used to send the batch request, taking the same arguments as the global `fetch()`.
* Defaults to the global `fetch`. Useful for runtimes where requests must go through a special
* fetch function, such as a VPC or service binding, or for instrumenting requests.
*
* The function is called unbound, so wrap a method that needs its receiver, e.g.
* `(input, init) => env.VPC.fetch(input, init)` rather than `env.VPC.fetch`.
*/
fetch?: (input: string | Request, init?: RequestInit) => Promise<Response>;
};

export function newHttpBatchRpcSession(
urlOrRequest: string | Request, options?: RpcSessionOptions): RpcStub {
urlOrRequest: string | Request, options?: HttpBatchRpcSessionOptions): RpcStub {
let sendBatch: SendBatchFunc = async (batch: string[]) => {
let response = await fetch(urlOrRequest, {
// Look up the global `fetch` at send time (not at session creation) so that it behaves as it
// did before this option existed.
let fetchFunc = options?.fetch ?? fetch;

@ndisidore ndisidore Nov 22, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

called unbound, so { fetch: env.VPC.fetch } typechecks but throws Illegal invocation in workerd, which is the #66 use case. could also accept a { fetch } object and call it as a method?

let response = await fetchFunc(urlOrRequest, {
method: "POST",
body: batch.join("\n"),
});
Expand Down
17 changes: 11 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import { RpcTargetBranded, RpcCompatible, Stub, ElideStub, PayloadOrStub,
import { newWebSocketRpcSession as newWebSocketRpcSessionImpl,
newWorkersWebSocketRpcResponse, WebSocketTransport } from "./websocket.js";
import { newHttpBatchRpcSession as newHttpBatchRpcSessionImpl,
newHttpBatchRpcResponse, nodeHttpBatchRpcResponse } from "./batch.js";
newHttpBatchRpcResponse, nodeHttpBatchRpcResponse,
type HttpBatchRpcSessionOptions } from "./batch.js";
import { newMessagePortRpcSession as newMessagePortRpcSessionImpl } from "./messageport.js";
import { forceInitMap } from "./map.js";
import { forceInitStreams } from "./streams.js";
Expand All @@ -23,7 +24,7 @@ forceInitStreams();
export { serialize, deserialize, newWorkersWebSocketRpcResponse, newHttpBatchRpcResponse,
nodeHttpBatchRpcResponse, WebSocketTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH };
export type { RpcTransport, RpcTransportWithCustomEncoding, AnyRpcTransport,
RpcSessionOptions, RpcCompatible, EncodingLevel, RpcLimits };
RpcSessionOptions, HttpBatchRpcSessionOptions, RpcCompatible, EncodingLevel, RpcLimits };

// Hack the type system to make RpcStub's types work nicely!
/**
Expand Down Expand Up @@ -139,12 +140,16 @@ export let newWebSocketRpcSession:<T extends RpcCompatible<T> = Empty>
/**
* Initiate an HTTP batch session from the client side.
*
* The parameters to this method have exactly the same signature as `fetch()`, but the return
* value is an RpcStub. You can customize anything about the request except for the method
* (it will always be set to POST) and the body (which the RPC system will fill in).
* The first parameter is the same as the first parameter of `fetch()` (a URL or a Request), but the
* return value is an RpcStub. You can customize anything about the request except for the method
* (it will always be set to POST) and the body (which the RPC system will fill in). The second
* parameter is session options, not `RequestInit`.
*
* To send the request with something other than the global `fetch()`, pass a `fetch` function in
* `options`.
*/
export let newHttpBatchRpcSession:<T extends RpcCompatible<T>>
(urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub<T> =
(urlOrRequest: string | Request, options?: HttpBatchRpcSessionOptions) => RpcStub<T> =
<any>newHttpBatchRpcSessionImpl;

/**
Expand Down
Loading