Next.js Integration
On this page
tRPC + Next.js
Next.js makes it easy to build a client and server together in one codebase. tRPC makes it easy to share types between them, ensuring typesafety for your application's data fetching.
tRPC provides first-class support for both the App Router and the Pages Router. Choose the guide that matches your project:
App Router
The recommended approach for new Next.js projects. Uses React Server Components, the fetch adapter, and @trpc/tanstack-react-query.
Key features:
- Server Components - Prefetch data on the server and stream it to the client
- Streaming - Leverage Next.js streaming for optimal loading performance
- Suspense - Use
useSuspenseQuerywith Suspense boundaries for loading states
Pages Router
Uses the Next.js adapter for the API, and the same client as the App Router: @trpc/tanstack-react-query.
Key features:
- Server-side rendering - Prefetch a page's queries in
getServerSidePropsand render them into the first HTML. Read more about SSR. - Static site generation - Prefetch queries in
getStaticPropsand generate static HTML files. Read more about SSG.
Get started with Pages Router →
Choosing between App Router and Pages Router
| App Router | Pages Router | |
|---|---|---|
| Recommended for | New projects | Existing Pages Router projects |
| Data fetching | Server Components, prefetchQuery | prefetchQuery in getServerSideProps or getStaticProps |
| Server adapter | Fetch adapter | Next.js adapter |
| Client package | @trpc/tanstack-react-query | @trpc/tanstack-react-query |
| Provider setup | TRPCProvider in the root layout | TRPCProvider and HydrationBoundary in _app |