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.
- React Query:
@trpc/reactprovides a thin wrapper over react-query. It is required as a peer dependency.
- Zod: most examples use Zod for input validation, though it isn't required. You can use a validation library of your choice (Yup, io-ts, etc). In fact, any object containing a
validateSyncmethod will work.
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
View sample router
Create a set of strongly-typed hooks using your API's type signature.
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:
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:
urlyour API URL.
linksto customize the flow of data between tRPC Client and the tRPC-server. Read more.
queryClientConfig: a configuration object for the React Query
QueryClientused 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
fetchused by tRPC internally
AbortController: customize the implementation of
AbortControllerused by tRPC internally
Whether tRPC should await queries when server-side rendering a page. Defaults to