Custom Fetch

Override the fetch function used by the client. Useful for SSR (SvelteKit's platform fetch) and testing (mock fetch).

Default

When not specified, the client uses the global fetch.

ts
// Default: uses globalThis.fetch
const rpc = createRpcClient({ baseUrl: '/api' });

SSR (SvelteKit)

In SvelteKit server loads, pass the platform fetch to forward cookies and resolve relative URLs correctly.

ts
// SvelteKit server load — forward cookies & resolve relative URLs
export const load: PageServerLoad = async ({ fetch }) => {
  const rpc = createRpcClient({ baseUrl: '/api', fetch });
  const data = await rpc.query('cookie_demo');
  return { ssrResult: data };
};

Testing

Inject a mock fetch for unit tests without hitting the network.

ts
// Mock fetch for unit tests
const mockFetch = async (url: string) =>
  new Response(JSON.stringify({ ok: true }), { status: 200 });

const rpc = createRpcClient({ baseUrl: '/api', fetch: mockFetch });

Try it

The server checks for a session cookie. SSR event.fetch forwards it automatically; browser fetch does not (on Vercel, cross-origin).

SSR Result

Called during server load with event.fetch

✗ SSR error: RpcError: RPC error on "cookie_demo": 404

Client Result

Called from browser with default globalThis.fetch

visit GitHub to learn more about metaxy