If you're using tRPC in a new project, consider using one of the example projects as a starting point: 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.
- 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
trpc 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:
urlREQUIRED: Your API URL.
queryClientConfig: a configuration object for the React Query
QueryClientused internally by the tRPC React hooks: QueryClient docs
getHeaders: a function that returns a list of headers to be set on outgoing tRPC requests
transformer: a transformer applied to outgoing payloads. Read more about Data Transformers
FetchOptions: customize the implementation of
fetchused by tRPC internally
Whether tRPC should await queries when server-side rendering a page. Defaults to