Links & Request Batching

Similar to urql’s exchanges or Apollo’s links. Links enables you to customize the flow of data between tRPC Client and the tRPC-server.

Request Batching

Request batching is automatically enabled which batches your requests to the server, this can make the below code produce exactly one HTTP request and on the server exactly one database query:

  1. // below will be done in the same request when batching is enabled
  2. const somePosts = await Promise.all([
  3. client.query('post.byId', 1),
  4. client.query('post.byId', 2),
  5. client.query('post.byId', 3),
  6. ])

Customizing data flow

The below examples assuming you use Next.js, but the same as below can be added if you use the vanilla tRPC client

Setting a maximum batch size

This limits the number of requests that can be sent together in batch ( useful to prevent the url from getting too large and run into HTTP error 413 ).

server.ts

  1. import type { AppRouter } from 'pages/api/trpc/[trpc]';
  2. import { withTRPC } from '@trpc/next';
  3. import { AppType } from 'next/dist/shared/lib/utils';
  4. // 👇 import the httpBatchLink
  5. import { httpBatchLink } from '@trpc/client/links/httpBatchLink';
  6. const MyApp: AppType = ({ Component, pageProps }) => {
  7. return <Component {...pageProps} />;
  8. };
  9. export default withTRPC<AppRouter>({
  10. config() {
  11. return {
  12. links: [
  13. httpBatchLink({
  14. url: '/api/trpc',
  15. maxBatchSize: 10 // a reasonable size
  16. }),
  17. ],
  18. };
  19. },
  20. })(MyApp);

Disabling request batching

1. Disable batching on your server:

In your [trpc].ts:

pages/api/trpc/[trpc].ts

  1. export default trpcNext.createNextApiHandler({
  2. // [...]
  3. // 👇 disable batching
  4. batching: {
  5. enabled: false,
  6. },
  7. });

pages/_app.tsx

  1. import type { AppRouter } from 'pages/api/trpc/[trpc]';
  2. import { withTRPC } from '@trpc/next';
  3. import { AppType } from 'next/dist/shared/lib/utils';
  4. // 👇 import the httpLink
  5. import { httpLink } from '@trpc/client/links/httpLink';
  6. const MyApp: AppType = ({ Component, pageProps }) => {
  7. return <Component {...pageProps} />;
  8. };
  9. export default withTRPC<AppRouter>({
  10. config() {
  11. return {
  12. links: [
  13. httpLink({
  14. url: '/api/trpc',
  15. }),
  16. ],
  17. };
  18. },
  19. // ssr: false,
  20. })(MyApp);

Disable batching for certain requests

1. Configure client / _app.tsx

pages/_app.tsx

  1. import { withTRPC } from '@trpc/next';
  2. import { httpBatchLink } from '@trpc/client/links/httpBatchLink';
  3. import { httpLink } from '@trpc/client/links/httpLink';
  4. import { splitLink } from '@trpc/client/links/splitLink';
  5. // [..]
  6. export default withTRPC<AppRouter>({
  7. config() {
  8. const url = `http://localhost:3000`;
  9. return {
  10. links: [
  11. splitLink({
  12. condition(op) {
  13. // check for context property `skipBatch`
  14. return op.context.skipBatch === true;
  15. },
  16. // when condition is true, use normal request
  17. true: httpLink({
  18. url,
  19. }),
  20. // when condition is false, use batching
  21. false: httpBatchLink({
  22. url,
  23. }),
  24. }),
  25. ],
  26. };
  27. },
  28. })(MyApp);
2. Perform request without batching

MyComponent.tsx

  1. export function MyComponent() {
  2. const postsQuery = trpc.useQuery(['posts'], {
  3. context: {
  4. skipBatch: true,
  5. },
  6. });
  7. return (
  8. <pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>
  9. )
  10. })

or:

client.ts

  1. const postResult = client.query('posts', null, {
  2. context: {
  3. skipBatch: true,
  4. },
  5. })

pages/_app.tsx

  1. import type { AppRouter } from 'pages/api/trpc/[trpc]';
  2. import { TRPCLink } from '@trpc/client';
  3. const customLink: TRPCLink<AppRouter> = (runtime) => {
  4. // here we just got initialized in the app - this happens once per app
  5. // useful for storing cache for instance
  6. return ({ prev, next, op }) => {
  7. // this is when passing the result to the next link
  8. next(op, (result) => {
  9. // this is when we've gotten result from the server
  10. if (result instanceof Error) {
  11. // maybe send to bugsnag?
  12. }
  13. prev(result);
  14. });
  15. };
  16. };
  17. export default withTRPC<AppRouter>({
  18. config() {
  19. return {
  20. links: [
  21. customLink,
  22. // [..]
  23. // ❗ Make sure to end with a `httpBatchLink` or `httpLink`
  24. ],
  25. };
  26. },
  27. // ssr: false
  28. })(MyApp);