Next.js integration for tRPC that enables end-to-end type-safe APIs with enhanced server-side rendering and static site generation capabilities.
npx @tessl/cli install tessl/npm-trpc--next@11.5.00
# @trpc/next
1
2
@trpc/next is the Next.js integration library for tRPC that enables end-to-end type-safe APIs with enhanced server-side rendering and static site generation capabilities. It provides seamless client-server communication through React Query integration, automatic provider configuration, and comprehensive support for Next.js features including SSR, SSG, and client-side hydration.
3
4
## Package Information
5
6
- **Package Name**: @trpc/next
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @trpc/next @trpc/react-query @tanstack/react-query`
10
11
## Core Imports
12
13
```typescript
14
import { createTRPCNext, withTRPC } from "@trpc/next";
15
import { ssrPrepass } from "@trpc/next/ssrPrepass";
16
```
17
18
For specific App Router features:
19
20
```typescript
21
import { experimental_createTRPCNextAppDirClient } from "@trpc/next/app-dir/client";
22
import { experimental_createTRPCNextAppDirServer } from "@trpc/next/app-dir/server";
23
import { experimental_nextCacheLink } from "@trpc/next/app-dir/links/nextCache";
24
import { experimental_nextHttpLink } from "@trpc/next/app-dir/links/nextHttp";
25
```
26
27
## Basic Usage
28
29
### Pages Router Setup
30
31
```typescript
32
import { createTRPCNext } from "@trpc/next";
33
import { httpBatchLink } from "@trpc/client";
34
import type { AppRouter } from "../pages/api/[trpc]";
35
36
export const trpc = createTRPCNext<AppRouter>({
37
config() {
38
return {
39
links: [
40
httpBatchLink({
41
url: "http://localhost:3000/api/trpc",
42
}),
43
],
44
};
45
},
46
ssr: false,
47
});
48
49
// In _app.tsx
50
const App = ({ Component, pageProps }) => {
51
return <Component {...pageProps} />;
52
};
53
54
export default trpc.withTRPC(App);
55
```
56
57
### Using tRPC in Components
58
59
```typescript
60
import { trpc } from "~/utils/trpc";
61
62
export function UserProfile() {
63
const { data, error, status } = trpc.user.getProfile.useQuery({
64
userId: "123",
65
});
66
67
if (error) return <p>Error: {error.message}</p>;
68
if (status !== "success") return <p>Loading...</p>;
69
70
return <div>Welcome, {data.name}!</div>;
71
}
72
```
73
74
## Architecture
75
76
@trpc/next is built around several key architectural components:
77
78
- **Pages Router Integration**: Traditional Next.js pages with `withTRPC` HOC and `createTRPCNext` factory
79
- **App Router Support**: Experimental features for Next.js App Router with server components and server actions
80
- **SSR Engine**: Server-side rendering support with automatic query prefetching and hydration
81
- **Cache Management**: Integration with Next.js caching strategies and revalidation
82
- **Type Safety**: End-to-end TypeScript integration preserving types from server to client
83
- **React Query Integration**: Built on @tanstack/react-query for caching and synchronization
84
85
## Capabilities
86
87
### Pages Router Integration
88
89
Core integration for Next.js Pages Router providing HOC wrapping and tRPC hook creation. Essential for traditional Next.js applications.
90
91
```typescript { .api }
92
function createTRPCNext<TRouter extends AnyRouter, TSSRContext extends NextPageContext = NextPageContext>(
93
opts: WithTRPCNoSSROptions<TRouter> | WithTRPCSSROptions<TRouter>
94
): CreateTRPCNext<TRouter, TSSRContext>;
95
96
function withTRPC<TRouter extends AnyRouter, TSSRContext extends NextPageContext = NextPageContext>(
97
opts: WithTRPCNoSSROptions<TRouter> | WithTRPCSSROptions<TRouter>
98
): (AppOrPage: NextComponentType<any, any, any>) => NextComponentType;
99
```
100
101
[Pages Router Integration](./pages-router.md)
102
103
### Server-Side Rendering (SSR)
104
105
Advanced SSR capabilities with automatic query prefetching, cache dehydration/hydration, and response meta handling.
106
107
```typescript { .api }
108
export const ssrPrepass: TRPCPrepassHelper;
109
110
interface WithTRPCSSROptions<TRouter extends AnyRouter> extends WithTRPCOptions<TRouter> {
111
ssr: true | ((opts: { ctx: NextPageContext }) => boolean | Promise<boolean>);
112
responseMeta?: (opts: {
113
ctx: NextPageContext;
114
clientErrors: TRPCClientError<TRouter>[];
115
}) => ResponseMeta;
116
ssrPrepass: TRPCPrepassHelper;
117
}
118
```
119
120
[Server-Side Rendering](./ssr.md)
121
122
### App Router Support
123
124
Experimental features for Next.js App Router including server components, server actions, and advanced caching.
125
126
```typescript { .api }
127
function experimental_createTRPCNextAppDirClient<TRouter extends AnyRouter>(
128
opts: CreateTRPCNextAppRouterOptions<TRouter>
129
): TRPCClient<TRouter>;
130
131
function experimental_createTRPCNextAppDirServer<TRouter extends AnyRouter>(
132
opts: CreateTRPCNextAppRouterOptions<TRouter>
133
): NextAppDirDecorateRouterRecord<TRouter['_def']['_config']['$types'], TRouter['_def']['record']>;
134
```
135
136
[App Router Support](./app-router.md)
137
138
### Server Actions
139
140
Experimental server actions integration for form handling and mutations in App Router.
141
142
```typescript { .api }
143
function experimental_createActionHook<TInferrable extends InferrableClientTypes>(
144
opts: CreateTRPCClientOptions<TInferrable>
145
): <TDef extends ActionHandlerDef>(
146
handler: TRPCActionHandler<TDef>,
147
useActionOpts?: UseTRPCActionOptions<TDef>
148
) => UseTRPCActionResult<TDef>;
149
150
function experimental_createServerActionHandler<TInstance extends { _config: RootConfig<AnyRootTypes> }>(
151
t: TInstance,
152
opts: CreateContextCallback & ServerActionHandlerOptions
153
): <TProc extends AnyProcedure>(proc: TProc) => TRPCActionHandler<inferActionDef<TInstance, TProc>>;
154
```
155
156
[Server Actions](./server-actions.md)
157
158
### Cache Links
159
160
Specialized tRPC links for Next.js caching integration with cache tags and revalidation.
161
162
```typescript { .api }
163
function experimental_nextCacheLink<TRouter extends AnyRouter>(
164
opts: NextCacheLinkOptions<TRouter>
165
): TRPCLink<TRouter>;
166
167
function experimental_nextHttpLink<TRouter extends AnyRouter>(
168
opts: NextLinkSingleOptions<TRouter['_def']['_config']['$types']> | NextLinkBatchOptions<TRouter['_def']['_config']['$types']>
169
): TRPCLink<TRouter>;
170
```
171
172
[Cache Links](./cache-links.md)
173
174
## Core Types
175
176
```typescript { .api }
177
// Base router type from tRPC
178
interface AnyRouter {
179
_def: {
180
_config: {
181
$types: any;
182
};
183
record: any;
184
};
185
}
186
187
// Next.js page context type
188
interface NextPageContext {
189
req?: IncomingMessage;
190
res?: ServerResponse;
191
pathname: string;
192
query: ParsedUrlQuery;
193
asPath?: string;
194
}
195
196
// Configuration options for withTRPC HOC
197
interface WithTRPCConfig<TRouter extends AnyRouter> extends CreateTRPCClientOptions<TRouter>, CreateTRPCReactQueryClientConfig {
198
abortOnUnmount?: boolean;
199
}
200
201
// Return type from createTRPCNext with decorated router and utilities
202
interface CreateTRPCNext<TRouter extends AnyRouter, TSSRContext extends NextPageContext> {
203
useContext(): CreateReactUtils<TRouter, TSSRContext>;
204
useUtils(): CreateReactUtils<TRouter, TSSRContext>;
205
withTRPC: ReturnType<typeof withTRPC<TRouter, TSSRContext>>;
206
useQueries: TRPCUseQueries<TRouter>;
207
useSuspenseQueries: TRPCUseSuspenseQueries<TRouter>;
208
}
209
210
// Props passed during SSR prepass phase
211
interface TRPCPrepassProps<TRouter extends AnyRouter, TSSRContext extends NextPageContext = NextPageContext> {
212
config: WithTRPCConfig<TRouter>;
213
queryClient: QueryClient;
214
trpcClient: TRPCUntypedClient<TRouter> | TRPCClient<TRouter>;
215
ssrState: 'prepass';
216
ssrContext: TSSRContext;
217
}
218
219
// Function signature for SSR prepass helpers
220
type TRPCPrepassHelper = (opts: {
221
parent: WithTRPCSSROptions<AnyRouter>;
222
WithTRPC: NextComponentType<any, any, any>;
223
AppOrPage: NextComponentType<any, any, any>;
224
}) => void;
225
226
// App Router configuration options
227
interface CreateTRPCNextAppRouterOptions<TRouter extends AnyRouter> {
228
config: () => CreateTRPCClientOptions<TRouter>;
229
}
230
```