HTTP Batch Link

httpBatchLink is a terminating link that batches an array of individual tRPC operations into a single HTTP request that's sent to a single tRPC procedure.

httpBatchLink imported from trpc-nuxt/client is a convenience wrapper around the original httpBatchLink that replaces regular fetch with a $fetch from Nuxt. It also sets the default headers using useRequestHeaders.

Usage

You can import and add the httpBatchLink to the links array as such:

import { createTRPCNuxtClient, httpBatchLink } from 'trpc-nuxt/client'
import type { AppRouter } from '~/server/trpc/routers'

const client = createTRPCNuxtClient<AppRouter>({
  links: [
    httpBatchLink({
      url: '/api/trpc',
    }),
  ],
})

After that, you can make use of batching by setting all your procedures in a Promise.all. The code below will produce exactly one HTTP request and on the server exactly one database query:

const somePosts = await Promise.all([
  $client.post.byId.query(1);
  $client.post.byId.query(2);
  $client.post.byId.query(3);
])

The httpBatchLink function takes an options object that has the HTTPBatchLinkOptions shape.

export interface HttpBatchLinkOptions extends HTTPLinkOptions {
  maxURLLength?: number;
}

export interface HTTPLinkOptions {
  url: string;
  /**
   * Select headers to pass to `useRequestHeaders`.
   */
  pickHeaders?: string[];
  /**
   * Add ponyfill for fetch.
   */
  fetch?: typeof fetch;
  /**
   * Add ponyfill for AbortController
   */
  AbortController?: typeof AbortController | null;
  /**
   * Headers to be set on outgoing requests or a callback that of said headers
   * @link http://trpc.io/docs/v10/header
   */
  headers?: HTTPHeaders | (() => HTTPHeaders | Promise<HTTPHeaders>);
}

Setting a maximum URL length

When sending batch requests, sometimes the URL can become too large causing HTTP errors like 413 Payload Too Large, 414 URI Too Long, and 404 Not Found. The maxURLLength option will limit the number of requests that can be sent together in a batch.

import { createTRPCNuxtClient, httpBatchLink } from 'trpc-nuxt/client';
import type { AppRouter } from '~/server/trpc/routers'

const client = createTRPCNuxtClient<AppRouter>({
  links: [
    httpBatchLink({
      url: '/api/trpc',
      maxURLLength: 2083, // a suitable size
    }),
  ],
});