@trpc/server 11.22.1 → 11.22.2-canary.11.4427f0bea
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -8
- package/dist/adapters/aws-lambda/index.d.cts +1 -1
- package/dist/adapters/aws-lambda/index.d.mts +1 -1
- package/dist/adapters/express.d.cts +2 -2
- package/dist/adapters/express.d.mts +2 -2
- package/dist/adapters/fastify/index.d.cts +3 -3
- package/dist/adapters/fastify/index.d.mts +3 -3
- package/dist/adapters/fetch/index.d.cts +1 -1
- package/dist/adapters/fetch/index.d.mts +1 -1
- package/dist/adapters/next-app-dir.d.cts +2 -2
- package/dist/adapters/next-app-dir.d.mts +2 -2
- package/dist/adapters/next-app-dir.mjs.map +1 -1
- package/dist/adapters/next.d.cts +2 -2
- package/dist/adapters/next.d.mts +2 -2
- package/dist/adapters/node-http/index.d.cts +1 -1
- package/dist/adapters/node-http/index.d.mts +1 -1
- package/dist/adapters/standalone.d.cts +2 -2
- package/dist/adapters/standalone.d.mts +2 -2
- package/dist/adapters/ws.d.cts +2 -1
- package/dist/adapters/ws.d.mts +2 -1
- package/dist/http.d.cts +1 -1
- package/dist/http.d.mts +1 -1
- package/dist/{index-D7foMQMh.d.cts → index-CtkOmZzm.d.mts} +2 -2
- package/dist/{index-DPj2-I1U.d.mts.map → index-CtkOmZzm.d.mts.map} +1 -1
- package/dist/{index-DPj2-I1U.d.mts → index-Tpw5OCTF.d.cts} +2 -2
- package/dist/{index-D7foMQMh.d.cts.map → index-Tpw5OCTF.d.cts.map} +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/rpc.d.cts +1 -1
- package/dist/rpc.d.mts +1 -1
- package/dist/shared.d.cts +1 -1
- package/dist/shared.d.mts +1 -1
- package/dist/{unstable-core-do-not-import-BkTO4Ekx.d.cts → unstable-core-do-not-import-B8epiErP.d.cts} +28 -3
- package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -0
- package/dist/{unstable-core-do-not-import-DElJf3aU.d.mts → unstable-core-do-not-import-Dbo98mkh.d.mts} +28 -3
- package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -0
- package/dist/unstable-core-do-not-import.d.cts +2 -2
- package/dist/unstable-core-do-not-import.d.mts +2 -2
- package/dist/{ws-BR3-CM6m.d.mts → ws-DD1ukLuC.d.cts} +9 -34
- package/dist/ws-DD1ukLuC.d.cts.map +1 -0
- package/dist/ws-DJ2SSChC.mjs.map +1 -1
- package/dist/{ws-CaI8wmsh.d.cts → ws-DT37N43e.d.mts} +9 -34
- package/dist/ws-DT37N43e.d.mts.map +1 -0
- package/package.json +24 -12
- package/src/adapters/next-app-dir/notFound.ts +1 -1
- package/src/adapters/next-app-dir/redirect.ts +1 -1
- package/src/adapters/ws.ts +5 -5
- package/src/unstable-core-do-not-import/types.ts +10 -4
- package/src/unstable-core-do-not-import.ts +1 -0
- package/bin/intent.js +0 -20
- package/dist/unstable-core-do-not-import-BkTO4Ekx.d.cts.map +0 -1
- package/dist/unstable-core-do-not-import-DElJf3aU.d.mts.map +0 -1
- package/dist/ws-BR3-CM6m.d.mts.map +0 -1
- package/dist/ws-CaI8wmsh.d.cts.map +0 -1
- package/skills/adapter-aws-lambda/SKILL.md +0 -203
- package/skills/adapter-express/SKILL.md +0 -176
- package/skills/adapter-fastify/SKILL.md +0 -221
- package/skills/adapter-fetch/SKILL.md +0 -199
- package/skills/adapter-standalone/SKILL.md +0 -198
- package/skills/auth/SKILL.md +0 -342
- package/skills/caching/SKILL.md +0 -205
- package/skills/error-handling/SKILL.md +0 -253
- package/skills/middlewares/SKILL.md +0 -242
- package/skills/non-json-content-types/SKILL.md +0 -265
- package/skills/server-setup/SKILL.md +0 -378
- package/skills/server-side-calls/SKILL.md +0 -249
- package/skills/service-oriented-architecture/SKILL.md +0 -247
- package/skills/subscriptions/SKILL.md +0 -406
- package/skills/trpc-router/SKILL.md +0 -151
- package/skills/validators/SKILL.md +0 -228
package/skills/auth/SKILL.md
DELETED
|
@@ -1,342 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: auth
|
|
3
|
-
description: >
|
|
4
|
-
Implement JWT/cookie authentication and authorization in tRPC using createContext
|
|
5
|
-
for user extraction, t.middleware with opts.next({ ctx }) for context narrowing to
|
|
6
|
-
non-null user, protectedProcedure base pattern, client-side Authorization headers
|
|
7
|
-
via httpBatchLink headers(), WebSocket connectionParams, and SSE auth via cookies
|
|
8
|
-
or EventSource polyfill custom headers.
|
|
9
|
-
type: composition
|
|
10
|
-
library: trpc
|
|
11
|
-
library_version: '11.16.0'
|
|
12
|
-
requires:
|
|
13
|
-
- server-setup
|
|
14
|
-
- middlewares
|
|
15
|
-
- client-setup
|
|
16
|
-
sources:
|
|
17
|
-
- www/docs/server/authorization.md
|
|
18
|
-
- www/docs/client/headers.md
|
|
19
|
-
- www/docs/client/links/httpSubscriptionLink.md
|
|
20
|
-
- www/docs/server/websockets.md
|
|
21
|
-
---
|
|
22
|
-
|
|
23
|
-
# tRPC — Auth
|
|
24
|
-
|
|
25
|
-
## Setup
|
|
26
|
-
|
|
27
|
-
```ts
|
|
28
|
-
// server/trpc.ts
|
|
29
|
-
import { initTRPC, TRPCError } from '@trpc/server';
|
|
30
|
-
import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
|
|
31
|
-
|
|
32
|
-
export async function createContext({ req }: CreateHTTPContextOptions) {
|
|
33
|
-
async function getUserFromHeader() {
|
|
34
|
-
const token = req.headers.authorization?.split(' ')[1];
|
|
35
|
-
if (token) {
|
|
36
|
-
const user = await verifyJwt(token); // your JWT verification
|
|
37
|
-
return user; // e.g. { id: string; name: string; role: string }
|
|
38
|
-
}
|
|
39
|
-
return null;
|
|
40
|
-
}
|
|
41
|
-
return { user: await getUserFromHeader() };
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
45
|
-
|
|
46
|
-
const t = initTRPC.context<Context>().create();
|
|
47
|
-
|
|
48
|
-
export const publicProcedure = t.procedure;
|
|
49
|
-
|
|
50
|
-
export const protectedProcedure = t.procedure.use(
|
|
51
|
-
async function isAuthed(opts) {
|
|
52
|
-
const { ctx } = opts;
|
|
53
|
-
if (!ctx.user) {
|
|
54
|
-
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
|
55
|
-
}
|
|
56
|
-
return opts.next({
|
|
57
|
-
ctx: {
|
|
58
|
-
user: ctx.user, // narrows user to non-null
|
|
59
|
-
},
|
|
60
|
-
});
|
|
61
|
-
},
|
|
62
|
-
);
|
|
63
|
-
|
|
64
|
-
export const router = t.router;
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
```ts
|
|
68
|
-
// client/trpc.ts
|
|
69
|
-
import { createTRPCClient, httpBatchLink } from '@trpc/client';
|
|
70
|
-
import type { AppRouter } from '../server/router';
|
|
71
|
-
|
|
72
|
-
let token = '';
|
|
73
|
-
export function setToken(t: string) {
|
|
74
|
-
token = t;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export const trpc = createTRPCClient<AppRouter>({
|
|
78
|
-
links: [
|
|
79
|
-
httpBatchLink({
|
|
80
|
-
url: 'http://localhost:3000/trpc',
|
|
81
|
-
headers() {
|
|
82
|
-
return { Authorization: `Bearer ${token}` };
|
|
83
|
-
},
|
|
84
|
-
}),
|
|
85
|
-
],
|
|
86
|
-
});
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
## Core Patterns
|
|
90
|
-
|
|
91
|
-
### Context narrowing with auth middleware
|
|
92
|
-
|
|
93
|
-
```ts
|
|
94
|
-
import { initTRPC, TRPCError } from '@trpc/server';
|
|
95
|
-
|
|
96
|
-
type Context = { user: { id: string; role: string } | null };
|
|
97
|
-
const t = initTRPC.context<Context>().create();
|
|
98
|
-
|
|
99
|
-
const isAuthed = t.middleware(async ({ ctx, next }) => {
|
|
100
|
-
if (!ctx.user) {
|
|
101
|
-
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
|
102
|
-
}
|
|
103
|
-
return next({ ctx: { user: ctx.user } });
|
|
104
|
-
});
|
|
105
|
-
|
|
106
|
-
const isAdmin = t.middleware(async ({ ctx, next }) => {
|
|
107
|
-
if (!ctx.user || ctx.user.role !== 'admin') {
|
|
108
|
-
throw new TRPCError({ code: 'FORBIDDEN' });
|
|
109
|
-
}
|
|
110
|
-
return next({ ctx: { user: ctx.user } });
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
export const protectedProcedure = t.procedure.use(isAuthed);
|
|
114
|
-
export const adminProcedure = t.procedure.use(isAdmin);
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
### SSE subscription auth with EventSource polyfill
|
|
118
|
-
|
|
119
|
-
```ts
|
|
120
|
-
import {
|
|
121
|
-
createTRPCClient,
|
|
122
|
-
httpBatchLink,
|
|
123
|
-
httpSubscriptionLink,
|
|
124
|
-
splitLink,
|
|
125
|
-
} from '@trpc/client';
|
|
126
|
-
import { EventSourcePolyfill } from 'event-source-polyfill';
|
|
127
|
-
import type { AppRouter } from '../server/router';
|
|
128
|
-
|
|
129
|
-
const trpc = createTRPCClient<AppRouter>({
|
|
130
|
-
links: [
|
|
131
|
-
splitLink({
|
|
132
|
-
condition: (op) => op.type === 'subscription',
|
|
133
|
-
true: httpSubscriptionLink({
|
|
134
|
-
url: 'http://localhost:3000/trpc',
|
|
135
|
-
EventSource: EventSourcePolyfill,
|
|
136
|
-
eventSourceOptions: async () => {
|
|
137
|
-
return {
|
|
138
|
-
headers: {
|
|
139
|
-
authorization: `Bearer ${getToken()}`,
|
|
140
|
-
},
|
|
141
|
-
};
|
|
142
|
-
},
|
|
143
|
-
}),
|
|
144
|
-
false: httpBatchLink({
|
|
145
|
-
url: 'http://localhost:3000/trpc',
|
|
146
|
-
headers() {
|
|
147
|
-
return { Authorization: `Bearer ${getToken()}` };
|
|
148
|
-
},
|
|
149
|
-
}),
|
|
150
|
-
}),
|
|
151
|
-
],
|
|
152
|
-
});
|
|
153
|
-
```
|
|
154
|
-
|
|
155
|
-
### WebSocket auth with connectionParams
|
|
156
|
-
|
|
157
|
-
```ts
|
|
158
|
-
// server/context.ts
|
|
159
|
-
import type { CreateWSSContextFnOptions } from '@trpc/server/adapters/ws';
|
|
160
|
-
|
|
161
|
-
export const createContext = async (opts: CreateWSSContextFnOptions) => {
|
|
162
|
-
const token = opts.info.connectionParams?.token;
|
|
163
|
-
const user = token ? await verifyJwt(token) : null;
|
|
164
|
-
return { user };
|
|
165
|
-
};
|
|
166
|
-
```
|
|
167
|
-
|
|
168
|
-
```ts
|
|
169
|
-
// client/trpc.ts
|
|
170
|
-
import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
|
|
171
|
-
import type { AppRouter } from '../server/router';
|
|
172
|
-
|
|
173
|
-
const wsClient = createWSClient({
|
|
174
|
-
url: 'ws://localhost:3001',
|
|
175
|
-
connectionParams: async () => ({
|
|
176
|
-
token: getToken(),
|
|
177
|
-
}),
|
|
178
|
-
});
|
|
179
|
-
|
|
180
|
-
const trpc = createTRPCClient<AppRouter>({
|
|
181
|
-
links: [wsLink({ client: wsClient })],
|
|
182
|
-
});
|
|
183
|
-
```
|
|
184
|
-
|
|
185
|
-
### SSE auth with cookies (same domain)
|
|
186
|
-
|
|
187
|
-
```ts
|
|
188
|
-
import {
|
|
189
|
-
createTRPCClient,
|
|
190
|
-
httpBatchLink,
|
|
191
|
-
httpSubscriptionLink,
|
|
192
|
-
splitLink,
|
|
193
|
-
} from '@trpc/client';
|
|
194
|
-
import type { AppRouter } from '../server/router';
|
|
195
|
-
|
|
196
|
-
const trpc = createTRPCClient<AppRouter>({
|
|
197
|
-
links: [
|
|
198
|
-
splitLink({
|
|
199
|
-
condition: (op) => op.type === 'subscription',
|
|
200
|
-
true: httpSubscriptionLink({
|
|
201
|
-
url: '/api/trpc',
|
|
202
|
-
eventSourceOptions() {
|
|
203
|
-
return { withCredentials: true };
|
|
204
|
-
},
|
|
205
|
-
}),
|
|
206
|
-
false: httpBatchLink({ url: '/api/trpc' }),
|
|
207
|
-
}),
|
|
208
|
-
],
|
|
209
|
-
});
|
|
210
|
-
```
|
|
211
|
-
|
|
212
|
-
## Common Mistakes
|
|
213
|
-
|
|
214
|
-
### HIGH Not narrowing user type in auth middleware
|
|
215
|
-
|
|
216
|
-
Wrong:
|
|
217
|
-
|
|
218
|
-
```ts
|
|
219
|
-
const authMiddleware = t.middleware(async ({ ctx, next }) => {
|
|
220
|
-
if (!ctx.user) throw new TRPCError({ code: 'UNAUTHORIZED' });
|
|
221
|
-
return next(); // user still nullable downstream
|
|
222
|
-
});
|
|
223
|
-
```
|
|
224
|
-
|
|
225
|
-
Correct:
|
|
226
|
-
|
|
227
|
-
```ts
|
|
228
|
-
const authMiddleware = t.middleware(async ({ ctx, next }) => {
|
|
229
|
-
if (!ctx.user) throw new TRPCError({ code: 'UNAUTHORIZED' });
|
|
230
|
-
return next({ ctx: { user: ctx.user } }); // narrows to non-null
|
|
231
|
-
});
|
|
232
|
-
```
|
|
233
|
-
|
|
234
|
-
Without `opts.next({ ctx })`, downstream procedures still see `user` as `{ id: string } | null`, requiring redundant null checks.
|
|
235
|
-
|
|
236
|
-
Source: www/docs/server/authorization.md
|
|
237
|
-
|
|
238
|
-
### HIGH SSE auth via URL query params exposes tokens
|
|
239
|
-
|
|
240
|
-
Wrong:
|
|
241
|
-
|
|
242
|
-
```ts
|
|
243
|
-
httpSubscriptionLink({
|
|
244
|
-
url: 'http://localhost:3000/trpc',
|
|
245
|
-
connectionParams: async () => ({
|
|
246
|
-
token: 'my-secret-jwt',
|
|
247
|
-
}),
|
|
248
|
-
});
|
|
249
|
-
```
|
|
250
|
-
|
|
251
|
-
Correct:
|
|
252
|
-
|
|
253
|
-
```ts
|
|
254
|
-
import { EventSourcePolyfill } from 'event-source-polyfill';
|
|
255
|
-
|
|
256
|
-
httpSubscriptionLink({
|
|
257
|
-
url: 'http://localhost:3000/trpc',
|
|
258
|
-
EventSource: EventSourcePolyfill,
|
|
259
|
-
eventSourceOptions: async () => ({
|
|
260
|
-
headers: { authorization: 'Bearer my-secret-jwt' },
|
|
261
|
-
}),
|
|
262
|
-
});
|
|
263
|
-
```
|
|
264
|
-
|
|
265
|
-
`connectionParams` are serialized as URL query strings for SSE, exposing tokens in server logs and browser history. Use cookies for same-domain or custom headers via an EventSource polyfill instead.
|
|
266
|
-
|
|
267
|
-
Source: www/docs/client/links/httpSubscriptionLink.md
|
|
268
|
-
|
|
269
|
-
### MEDIUM Async headers causing stuck isFetching
|
|
270
|
-
|
|
271
|
-
Wrong:
|
|
272
|
-
|
|
273
|
-
```ts
|
|
274
|
-
httpBatchLink({
|
|
275
|
-
url: '/api/trpc',
|
|
276
|
-
async headers() {
|
|
277
|
-
const token = await refreshToken(); // can race
|
|
278
|
-
return { Authorization: `Bearer ${token}` };
|
|
279
|
-
},
|
|
280
|
-
});
|
|
281
|
-
```
|
|
282
|
-
|
|
283
|
-
Correct:
|
|
284
|
-
|
|
285
|
-
```ts
|
|
286
|
-
let cachedToken: string | null = null;
|
|
287
|
-
|
|
288
|
-
async function ensureToken() {
|
|
289
|
-
if (!cachedToken) cachedToken = await refreshToken();
|
|
290
|
-
return cachedToken;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
httpBatchLink({
|
|
294
|
-
url: '/api/trpc',
|
|
295
|
-
async headers() {
|
|
296
|
-
return { Authorization: `Bearer ${await ensureToken()}` };
|
|
297
|
-
},
|
|
298
|
-
});
|
|
299
|
-
```
|
|
300
|
-
|
|
301
|
-
When the headers function is async (e.g., refreshing auth tokens), React Query's `isFetching` can get stuck permanently in certain race conditions.
|
|
302
|
-
|
|
303
|
-
Source: https://github.com/trpc/trpc/issues/7001
|
|
304
|
-
|
|
305
|
-
### HIGH Skipping auth or opening CORS too wide in prototypes
|
|
306
|
-
|
|
307
|
-
Wrong:
|
|
308
|
-
|
|
309
|
-
```ts
|
|
310
|
-
import cors from 'cors';
|
|
311
|
-
|
|
312
|
-
createHTTPServer({
|
|
313
|
-
middleware: cors(), // origin: '*' by default
|
|
314
|
-
router: appRouter,
|
|
315
|
-
createContext() {
|
|
316
|
-
return {};
|
|
317
|
-
}, // no auth
|
|
318
|
-
}).listen(3000);
|
|
319
|
-
```
|
|
320
|
-
|
|
321
|
-
Correct:
|
|
322
|
-
|
|
323
|
-
```ts
|
|
324
|
-
import cors from 'cors';
|
|
325
|
-
|
|
326
|
-
createHTTPServer({
|
|
327
|
-
middleware: cors({ origin: 'https://myapp.com' }),
|
|
328
|
-
router: appRouter,
|
|
329
|
-
createContext,
|
|
330
|
-
}).listen(3000);
|
|
331
|
-
```
|
|
332
|
-
|
|
333
|
-
Wildcard CORS and missing auth middleware are acceptable only during local development. Always restrict CORS origins and add auth before deploying.
|
|
334
|
-
|
|
335
|
-
Source: maintainer interview
|
|
336
|
-
|
|
337
|
-
## See Also
|
|
338
|
-
|
|
339
|
-
- **middlewares** -- context narrowing, `.use()`, `.concat()`, base procedure patterns
|
|
340
|
-
- **subscriptions** -- SSE and WebSocket transport setup for authenticated subscriptions
|
|
341
|
-
- **client-setup** -- `createTRPCClient`, link chain, `headers` option
|
|
342
|
-
- **links** -- `splitLink`, `httpSubscriptionLink`, `wsLink` configuration
|
package/skills/caching/SKILL.md
DELETED
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: caching
|
|
3
|
-
description: >
|
|
4
|
-
Set HTTP cache headers on tRPC query responses via responseMeta callback for
|
|
5
|
-
CDN and browser caching. Configure Cache-Control, s-maxage,
|
|
6
|
-
stale-while-revalidate. Handle caching with batching and authenticated requests.
|
|
7
|
-
Avoid caching mutations, errors, and authenticated responses.
|
|
8
|
-
type: core
|
|
9
|
-
library: trpc
|
|
10
|
-
library_version: '11.16.0'
|
|
11
|
-
requires:
|
|
12
|
-
- server-setup
|
|
13
|
-
sources:
|
|
14
|
-
- 'trpc/trpc:www/docs/server/caching.md'
|
|
15
|
-
---
|
|
16
|
-
|
|
17
|
-
# tRPC -- Caching
|
|
18
|
-
|
|
19
|
-
## Setup
|
|
20
|
-
|
|
21
|
-
```ts
|
|
22
|
-
// server/trpc.ts
|
|
23
|
-
import { initTRPC } from '@trpc/server';
|
|
24
|
-
import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
|
|
25
|
-
|
|
26
|
-
export const createContext = async (opts: CreateHTTPContextOptions) => {
|
|
27
|
-
return {
|
|
28
|
-
req: opts.req,
|
|
29
|
-
res: opts.res,
|
|
30
|
-
user: null as { id: string } | null,
|
|
31
|
-
};
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
type Context = Awaited<ReturnType<typeof createContext>>;
|
|
35
|
-
|
|
36
|
-
export const t = initTRPC.context<Context>().create();
|
|
37
|
-
export const router = t.router;
|
|
38
|
-
export const publicProcedure = t.procedure;
|
|
39
|
-
```
|
|
40
|
-
|
|
41
|
-
```ts
|
|
42
|
-
// server/appRouter.ts
|
|
43
|
-
import { publicProcedure, router } from './trpc';
|
|
44
|
-
|
|
45
|
-
export const appRouter = router({
|
|
46
|
-
public: router({
|
|
47
|
-
slowQueryCached: publicProcedure.query(async () => {
|
|
48
|
-
await new Promise((resolve) => setTimeout(resolve, 5000));
|
|
49
|
-
return { lastUpdated: new Date().toJSON() };
|
|
50
|
-
}),
|
|
51
|
-
}),
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
export type AppRouter = typeof appRouter;
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
```ts
|
|
58
|
-
// server/index.ts
|
|
59
|
-
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
60
|
-
import { appRouter } from './appRouter';
|
|
61
|
-
import { createContext } from './trpc';
|
|
62
|
-
|
|
63
|
-
const server = createHTTPServer({
|
|
64
|
-
router: appRouter,
|
|
65
|
-
createContext,
|
|
66
|
-
responseMeta(opts) {
|
|
67
|
-
const { paths, errors, type } = opts;
|
|
68
|
-
|
|
69
|
-
const allPublic =
|
|
70
|
-
paths && paths.every((path) => path.startsWith('public.'));
|
|
71
|
-
const allOk = errors.length === 0;
|
|
72
|
-
const isQuery = type === 'query';
|
|
73
|
-
|
|
74
|
-
if (allPublic && allOk && isQuery) {
|
|
75
|
-
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
|
|
76
|
-
return {
|
|
77
|
-
headers: new Headers([
|
|
78
|
-
[
|
|
79
|
-
'cache-control',
|
|
80
|
-
`s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
|
|
81
|
-
],
|
|
82
|
-
]),
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
return {};
|
|
86
|
-
},
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
server.listen(3000);
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
## Core Patterns
|
|
93
|
-
|
|
94
|
-
### Path-based public route caching
|
|
95
|
-
|
|
96
|
-
```ts
|
|
97
|
-
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
98
|
-
import { appRouter } from './appRouter';
|
|
99
|
-
import { createContext } from './trpc';
|
|
100
|
-
|
|
101
|
-
const server = createHTTPServer({
|
|
102
|
-
router: appRouter,
|
|
103
|
-
createContext,
|
|
104
|
-
responseMeta({ paths, errors, type }) {
|
|
105
|
-
const allPublic =
|
|
106
|
-
paths && paths.every((path) => path.startsWith('public.'));
|
|
107
|
-
const allOk = errors.length === 0;
|
|
108
|
-
const isQuery = type === 'query';
|
|
109
|
-
|
|
110
|
-
if (allPublic && allOk && isQuery) {
|
|
111
|
-
return {
|
|
112
|
-
headers: new Headers([
|
|
113
|
-
['cache-control', 's-maxage=1, stale-while-revalidate=86400'],
|
|
114
|
-
]),
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
return {};
|
|
118
|
-
},
|
|
119
|
-
});
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
Name public routes with a `public` prefix (e.g., `public.slowQueryCached`) so `responseMeta` can identify them by path.
|
|
123
|
-
|
|
124
|
-
### Skip caching for authenticated requests
|
|
125
|
-
|
|
126
|
-
```ts
|
|
127
|
-
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
128
|
-
import { appRouter } from './appRouter';
|
|
129
|
-
import { createContext } from './trpc';
|
|
130
|
-
|
|
131
|
-
const server = createHTTPServer({
|
|
132
|
-
router: appRouter,
|
|
133
|
-
createContext,
|
|
134
|
-
responseMeta({ ctx, errors, type }) {
|
|
135
|
-
if (ctx?.user || errors.length > 0 || type !== 'query') {
|
|
136
|
-
return {};
|
|
137
|
-
}
|
|
138
|
-
return {
|
|
139
|
-
headers: new Headers([
|
|
140
|
-
['cache-control', 's-maxage=1, stale-while-revalidate=86400'],
|
|
141
|
-
]),
|
|
142
|
-
};
|
|
143
|
-
},
|
|
144
|
-
});
|
|
145
|
-
```
|
|
146
|
-
|
|
147
|
-
## Common Mistakes
|
|
148
|
-
|
|
149
|
-
### [CRITICAL] Caching authenticated responses
|
|
150
|
-
|
|
151
|
-
Wrong:
|
|
152
|
-
|
|
153
|
-
```ts
|
|
154
|
-
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
155
|
-
import { appRouter } from './appRouter';
|
|
156
|
-
|
|
157
|
-
const server = createHTTPServer({
|
|
158
|
-
router: appRouter,
|
|
159
|
-
responseMeta() {
|
|
160
|
-
return {
|
|
161
|
-
headers: new Headers([['cache-control', 's-maxage=60']]),
|
|
162
|
-
};
|
|
163
|
-
},
|
|
164
|
-
});
|
|
165
|
-
```
|
|
166
|
-
|
|
167
|
-
Correct:
|
|
168
|
-
|
|
169
|
-
```ts
|
|
170
|
-
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
171
|
-
import { appRouter } from './appRouter';
|
|
172
|
-
import { createContext } from './trpc';
|
|
173
|
-
|
|
174
|
-
const server = createHTTPServer({
|
|
175
|
-
router: appRouter,
|
|
176
|
-
createContext,
|
|
177
|
-
responseMeta({ ctx, errors, type }) {
|
|
178
|
-
if (ctx?.user || errors.length > 0 || type !== 'query') {
|
|
179
|
-
return {};
|
|
180
|
-
}
|
|
181
|
-
return {
|
|
182
|
-
headers: new Headers([
|
|
183
|
-
['cache-control', 's-maxage=1, stale-while-revalidate=86400'],
|
|
184
|
-
]),
|
|
185
|
-
};
|
|
186
|
-
},
|
|
187
|
-
});
|
|
188
|
-
```
|
|
189
|
-
|
|
190
|
-
With batching enabled by default, a cached response containing personal data could be served to other users; always check for auth context, errors, and request type before setting cache headers.
|
|
191
|
-
|
|
192
|
-
Source: www/docs/server/caching.md
|
|
193
|
-
|
|
194
|
-
### [HIGH] Next.js App Router overrides Cache-Control headers
|
|
195
|
-
|
|
196
|
-
There is no code fix for this -- Next.js App Router overrides `Cache-Control` headers set by tRPC via `responseMeta`. The documented caching approach using `responseMeta` does not work as expected in App Router. Use Next.js native caching mechanisms (`revalidate`, `unstable_cache`) instead when deploying on App Router.
|
|
197
|
-
|
|
198
|
-
Source: https://github.com/trpc/trpc/issues/5625
|
|
199
|
-
|
|
200
|
-
## See Also
|
|
201
|
-
|
|
202
|
-
- `server-setup` -- initTRPC, createContext configuration
|
|
203
|
-
- `adapter-standalone` -- responseMeta option on createHTTPServer
|
|
204
|
-
- `adapter-fetch` -- responseMeta option on fetchRequestHandler
|
|
205
|
-
- `links` -- splitLink to separate public/private requests on the client
|