Usage with Next.js

tip

If you’re using tRPC in a new project, consider using one of the example projects as a starting point or for reference: tRPC Example Projects

tRPC and Next.js are a match made in heaven! Next.js makes it easy for you to build your client and server together in one codebase. This makes it easy to share types between them.

tRPC includes dedicated tools to make the Next.js developer experience as seamless as possible.

Recommended but not enforced file structure. This is what you get when starting from the examples.

  1. .
  2. ├── prisma # <-- if prisma is added
  3. └── [..]
  4. ├── src
  5. ├── pages
  6. ├── _app.tsx # <-- add `withTRPC()`-HOC here
  7. ├── api
  8. └── trpc
  9. └── [trpc].ts # <-- tRPC HTTP handler
  10. └── [..]
  11. ├── server
  12. ├── routers
  13. ├── app.ts # <-- main app router
  14. ├── post.ts # <-- sub routers
  15. └── [..]
  16. ├── context.ts # <-- create app context
  17. └── createRouter.ts # <-- router helper
  18. └── utils
  19. └── trpc.ts # <-- your typesafe tRPC hooks
  20. └── [..]

Add tRPC to existing Next.js project

1. Install deps

  1. yarn add @trpc/client @trpc/server @trpc/react @trpc/next zod react-query
  • React Query: @trpc/react provides a thin wrapper over react-query. It is required as a peer dependency.
  • Zod: most examples use Zod for input validation and we highly recommended it, though it isn’t required. You can use a validation library of your choice (Yup, Superstruct, io-ts, etc). In fact, any object containing a parse, create or validateSync method will work.

2. Enable strict mode

If you want to use Zod for input validation, make sure you have enabled strict mode in your tsconfig.json:

  1. // tsconfig.json
  2. {
  3. // ...
  4. "compilerOptions": {
  5. // ...
  6. "strict": true
  7. }
  8. }

If strict mode is too much, at least enable strictNullChecks:

  1. // tsconfig.json
  2. {
  3. // ...
  4. "compilerOptions": {
  5. // ...
  6. "strictNullChecks": true
  7. }
  8. }

3. Create a tRPC router

Implement your tRPC router in ./pages/api/trpc/[trpc].ts. If you need to split your router into several subrouters, implement them in a top-level server directory in your project root, then import them into ./pages/api/trpc/[trpc].ts and merge them into a single root appRouter.

View sample router

./pages/api/trpc/[trpc].ts

  1. import * as trpc from '@trpc/server';
  2. import * as trpcNext from '@trpc/server/adapters/next';
  3. import { z } from 'zod';
  4. export const appRouter = trpc
  5. .router()
  6. .query('hello', {
  7. input: z
  8. .object({
  9. text: z.string().nullish(),
  10. })
  11. .nullish(),
  12. resolve({ input }) {
  13. return {
  14. greeting: `hello ${input?.text ?? 'world'}`,
  15. };
  16. },
  17. });
  18. // export type definition of API
  19. export type AppRouter = typeof appRouter;
  20. // export API handler
  21. export default trpcNext.createNextApiHandler({
  22. router: appRouter,
  23. createContext: () => null,
  24. });

4. Create tRPC hooks

Create a set of strongly-typed hooks using your API’s type signature.

utils/trpc.ts

  1. import { createReactQueryHooks } from '@trpc/react';
  2. import type { AppRouter } from '../pages/api/trpc/[trpc]';
  3. export const trpc = createReactQueryHooks<AppRouter>();
  4. // => { useQuery: ..., useMutation: ...}

5. Configure _app.tsx

The createReactQueryHooks function expects certain parameters to be passed via the Context API. To set these parameters, create a custom _app.tsx using the withTRPC higher-order component:

pages/_app.tsx

  1. import { withTRPC } from '@trpc/next';
  2. import { AppType } from 'next/dist/shared/lib/utils';
  3. import { AppRouter } from './api/trpc/[trpc]';
  4. const MyApp: AppType = ({ Component, pageProps }) => {
  5. return <Component {...pageProps} />;
  6. };
  7. export default withTRPC<AppRouter>({
  8. config({ ctx }) {
  9. /**
  10. * If you want to use SSR, you need to use the server's full URL
  11. * @link https://trpc.io/docs/ssr
  12. */
  13. const url = process.env.VERCEL_URL
  14. ? `https://${process.env.VERCEL_URL}/api/trpc`
  15. : 'http://localhost:3000/api/trpc';
  16. return {
  17. url,
  18. /**
  19. * @link https://react-query.tanstack.com/reference/QueryClient
  20. */
  21. // queryClientConfig: { defaultOptions: { queries: { staleTime: 60 } } },
  22. };
  23. },
  24. /**
  25. * @link https://trpc.io/docs/ssr
  26. */
  27. ssr: true,
  28. })(MyApp);

6. Make API requests

pages/index.ts

  1. import { trpc } from '../utils/trpc';
  2. export default function IndexPage() {
  3. const hello = trpc.useQuery(['hello', { text: 'client' }]);
  4. if (!hello.data) {
  5. return <div>Loading...</div>;
  6. }
  7. return (
  8. <div>
  9. <p>{hello.data.greeting}</p>
  10. </div>
  11. );
  12. };

withTRPC() options

config-callback

The config-argument is a function that returns an object that configures the tRPC and React Query clients. This function has a ctx input that gives you access to the Next.js req object, among other things. The returned value can contain the following properties:

  • Exactly one of these are required:

    • url your API URL.
    • links to customize the flow of data between tRPC Client and the tRPC-server. Read more.
  • Optional:

    • queryClientConfig: a configuration object for the React Query QueryClient used internally by the tRPC React hooks: QueryClient docs
    • headers: an object or a function that returns an object of outgoing tRPC requests
    • transformer: a transformer applied to outgoing payloads. Read more about Data Transformers
    • fetch: customize the implementation of fetch used by tRPC internally
    • AbortController: customize the implementation of AbortController used by tRPC internally

ssr-boolean (default: false)

Whether tRPC should await queries when server-side rendering a page. Defaults to false.

responseMeta-callback

Ability to set request headers and HTTP status when server-side rendering.

Example

pages/_app.tsx

  1. export default withTRPC<AppRouter>({
  2. config({ ctx }) {
  3. /* [...] */
  4. },
  5. ssr: true,
  6. responseMeta({ clientErrors, ctx }) {
  7. if (clientErrors.length) {
  8. // propagate first http error from API calls
  9. return {
  10. status: clientErrors[0].data?.httpStatus ?? 500,
  11. };
  12. }
  13. // cache full page for 1 day + revalidate once every second
  14. const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
  15. return {
  16. 'Cache-Control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
  17. };
  18. },
  19. })(MyApp);

Next steps

Refer to the @trpc/react docs for additional information on executing Queries and Mutations inside your components.