@trpc/server 11.22.2-canary.7.c01346ec8 → 11.23.0
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.cjs +1 -1
- package/dist/adapters/aws-lambda/index.d.cts.map +1 -1
- package/dist/adapters/aws-lambda/index.d.mts.map +1 -1
- package/dist/adapters/aws-lambda/index.mjs +1 -1
- package/dist/adapters/aws-lambda/index.mjs.map +1 -1
- package/dist/adapters/express.cjs +1 -1
- package/dist/adapters/express.mjs +1 -1
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/fastify/index.cjs +3 -3
- package/dist/adapters/fastify/index.mjs +3 -3
- package/dist/adapters/fetch/index.cjs +1 -1
- package/dist/adapters/fetch/index.mjs +1 -1
- package/dist/adapters/next-app-dir.mjs.map +1 -1
- package/dist/adapters/next.cjs +1 -1
- package/dist/adapters/next.mjs +1 -1
- package/dist/adapters/next.mjs.map +1 -1
- package/dist/adapters/node-http/index.cjs +1 -1
- package/dist/adapters/node-http/index.mjs +1 -1
- package/dist/adapters/standalone.cjs +9 -3
- package/dist/adapters/standalone.d.cts +0 -1
- package/dist/adapters/standalone.d.cts.map +1 -1
- package/dist/adapters/standalone.d.mts +0 -1
- package/dist/adapters/standalone.d.mts.map +1 -1
- package/dist/adapters/standalone.mjs +9 -3
- package/dist/adapters/standalone.mjs.map +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.mjs +1 -1
- package/dist/asyncGeneratorDelegate-FcEJT04i.mjs.map +1 -1
- package/dist/codes-C9N0z0an.mjs.map +1 -1
- package/dist/getErrorShape-zlj81BiC.mjs.map +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.mjs +1 -1
- package/dist/initTRPC-RMeQIy9H.mjs.map +1 -1
- package/dist/{node-http-B5jkpWn7.mjs → node-http-ChhZEv1k.mjs} +2 -2
- package/dist/node-http-ChhZEv1k.mjs.map +1 -0
- package/dist/{node-http-BZ0HlzkC.cjs → node-http-X8RiQEuH.cjs} +1 -1
- package/dist/parseTRPCMessage-CJ4DJVBp.mjs.map +1 -1
- package/dist/{resolveResponse-b9D_SrLs.cjs → resolveResponse-CoGjFxK0.cjs} +8 -4
- package/dist/{resolveResponse-DH5L33sC.mjs → resolveResponse-DksrxZ2k.mjs} +9 -5
- package/dist/resolveResponse-DksrxZ2k.mjs.map +1 -0
- package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -1
- package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -1
- package/dist/unstable-core-do-not-import.cjs +1 -1
- package/dist/unstable-core-do-not-import.mjs +1 -1
- package/dist/unstable-core-do-not-import.mjs.map +1 -1
- package/dist/{ws-83TNWW-W.cjs → ws-7qWW7Uec.cjs} +2 -2
- package/dist/{ws-DJ2SSChC.mjs → ws-BYfo-HED.mjs} +3 -3
- package/dist/ws-BYfo-HED.mjs.map +1 -0
- package/package.json +9 -12
- package/skills/adapter-aws-lambda/SKILL.md +152 -134
- package/skills/adapter-express/SKILL.md +127 -113
- package/skills/adapter-fastify/SKILL.md +228 -136
- package/skills/adapter-fetch/SKILL.md +388 -111
- package/skills/adapter-standalone/SKILL.md +184 -94
- package/skills/auth/SKILL.md +327 -202
- package/skills/auth/references/client-cors.md +29 -0
- package/skills/caching/SKILL.md +58 -148
- package/skills/error-handling/SKILL.md +280 -174
- package/skills/middlewares/SKILL.md +320 -121
- package/skills/non-json-content-types/SKILL.md +149 -168
- package/skills/server-setup/SKILL.md +355 -253
- package/skills/server-setup/references/server-context.md +219 -0
- package/skills/server-setup/references/server-merging-routers.md +141 -0
- package/skills/server-setup/references/server-metadata.md +105 -0
- package/skills/server-setup/references/server-procedures.md +172 -0
- package/skills/server-setup/references/server-routers.md +123 -0
- package/skills/server-side-calls/SKILL.md +247 -152
- package/skills/service-oriented-architecture/SKILL.md +81 -177
- package/skills/subscriptions/SKILL.md +341 -297
- package/skills/subscriptions/references/client-links-httpSubscriptionLink.md +404 -0
- package/skills/subscriptions/references/client-links-wsLink.md +122 -0
- package/skills/subscriptions/references/server-websockets.md +297 -0
- package/skills/trpc-router/SKILL.md +156 -86
- package/skills/validators/SKILL.md +384 -128
- package/src/adapters/aws-lambda/getPlanner.ts +4 -3
- package/src/adapters/aws-lambda/index.ts +2 -1
- package/src/adapters/express.ts +1 -1
- package/src/adapters/next-app-dir/nextAppDirCaller.ts +4 -4
- package/src/adapters/next-app-dir/rethrowNextErrors.ts +1 -1
- package/src/adapters/next.ts +1 -1
- package/src/adapters/node-http/incomingMessageToRequest.ts +1 -1
- package/src/adapters/node-http/nodeHTTPRequestHandler.ts +1 -1
- package/src/adapters/node-http/types.ts +1 -1
- package/src/adapters/node-http/writeResponse.ts +1 -1
- package/src/adapters/standalone.ts +12 -6
- package/src/adapters/ws.ts +5 -5
- package/src/unstable-core-do-not-import/clientish/inferrable.ts +4 -1
- package/src/unstable-core-do-not-import/clientish/serialize.ts +4 -4
- package/src/unstable-core-do-not-import/error/TRPCError.ts +3 -3
- package/src/unstable-core-do-not-import/http/formDataToObject.ts +1 -1
- package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +1 -1
- package/src/unstable-core-do-not-import/http/resolveResponse.ts +13 -2
- package/src/unstable-core-do-not-import/procedure.ts +5 -2
- package/src/unstable-core-do-not-import/procedureBuilder.ts +3 -2
- package/src/unstable-core-do-not-import/rootConfig.ts +2 -2
- package/src/unstable-core-do-not-import/router.ts +5 -2
- package/src/unstable-core-do-not-import/rpc/envelopes.ts +3 -2
- package/src/unstable-core-do-not-import/stream/jsonl.ts +2 -1
- package/src/unstable-core-do-not-import/stream/sse.types.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/disposable.ts +6 -6
- package/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts +2 -2
- package/src/unstable-core-do-not-import/stream/utils/withPing.ts +3 -1
- package/src/unstable-core-do-not-import/transformer.ts +4 -1
- package/src/unstable-core-do-not-import/types.ts +3 -2
- package/src/unstable-core-do-not-import/utils.ts +1 -1
- package/src/vendor/standard-schema-v1/spec.ts +2 -2
- package/src/vendor/unpromise/unpromise.ts +1 -1
- package/bin/intent.js +0 -20
- package/dist/node-http-B5jkpWn7.mjs.map +0 -1
- package/dist/resolveResponse-DH5L33sC.mjs.map +0 -1
- package/dist/ws-DJ2SSChC.mjs.map +0 -1
package/skills/auth/SKILL.md
CHANGED
|
@@ -1,122 +1,253 @@
|
|
|
1
1
|
---
|
|
2
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'
|
|
3
|
+
description: Implement JWT/cookie authentication and authorization in tRPC using createContext for user extraction, t.middleware with opts.next({ ctx }) for context narrowing to non-null user, protectedProcedure base pattern, client-side Authorization headers via httpBatchLink headers(), WebSocket connectionParams, and SSE auth via cookies or EventSource polyfill custom headers. UNAUTHORIZED vs FORBIDDEN, role checks stacked on protectedProcedure, and why createContext shouldn't throw for a bad token.
|
|
12
4
|
requires:
|
|
13
5
|
- server-setup
|
|
14
6
|
- middlewares
|
|
15
7
|
- client-setup
|
|
16
8
|
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
|
|
9
|
+
- www/v11/docs/server/authorization.md
|
|
10
|
+
- www/v11/docs/client/headers.md
|
|
11
|
+
- www/v11/docs/client/links/httpSubscriptionLink.md
|
|
12
|
+
- www/v11/docs/server/websockets.md
|
|
13
|
+
- www/v11/docs/client/cors.md
|
|
14
|
+
metadata:
|
|
15
|
+
type: composition
|
|
16
|
+
library: trpc
|
|
17
|
+
library_version: 11.23.0
|
|
21
18
|
---
|
|
22
19
|
|
|
23
|
-
|
|
20
|
+
<!-- Generated from www/v11/docs/server/authorization.md by www/build/skills.ts. Edit the docs instead. -->
|
|
24
21
|
|
|
25
|
-
|
|
22
|
+
# Authorization
|
|
26
23
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
24
|
+
From https://trpc.io/docs/server/authorization
|
|
25
|
+
|
|
26
|
+
The `createContext` function is called for each incoming request, so here you can add contextual information about the calling user from the request object.
|
|
27
|
+
|
|
28
|
+
## Create context from request headers
|
|
29
|
+
|
|
30
|
+
```ts no-check title="server/context.ts"
|
|
30
31
|
import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
|
|
32
|
+
import { decodeAndVerifyJwtToken } from './utils';
|
|
33
|
+
|
|
34
|
+
export async function createContext({ req, res }: CreateHTTPContextOptions) {
|
|
35
|
+
// Create your context based on the request object
|
|
36
|
+
// Will be available as `ctx` in all your resolvers
|
|
31
37
|
|
|
32
|
-
|
|
38
|
+
// This is just an example of something you might want to do in your ctx fn
|
|
33
39
|
async function getUserFromHeader() {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
40
|
+
if (req.headers.authorization) {
|
|
41
|
+
const user = await decodeAndVerifyJwtToken(
|
|
42
|
+
req.headers.authorization.split(' ')[1],
|
|
43
|
+
);
|
|
44
|
+
return user;
|
|
38
45
|
}
|
|
39
46
|
return null;
|
|
40
47
|
}
|
|
41
|
-
|
|
42
|
-
}
|
|
48
|
+
const user = await getUserFromHeader();
|
|
43
49
|
|
|
50
|
+
return {
|
|
51
|
+
user,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
44
54
|
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
55
|
+
```
|
|
45
56
|
|
|
46
|
-
|
|
57
|
+
## Option 1: Authorize using resolver
|
|
58
|
+
|
|
59
|
+
```ts no-check title="server/routers/_app.ts"
|
|
60
|
+
import { initTRPC, TRPCError } from '@trpc/server';
|
|
61
|
+
import { z } from 'zod';
|
|
47
62
|
|
|
48
|
-
|
|
63
|
+
type Context = { user: { name: string } | null };
|
|
49
64
|
|
|
65
|
+
export const t = initTRPC.context<Context>().create();
|
|
66
|
+
|
|
67
|
+
const appRouter = t.router({
|
|
68
|
+
// open for anyone
|
|
69
|
+
hello: t.procedure
|
|
70
|
+
.input(z.string().nullish())
|
|
71
|
+
.query((opts) => `hello ${opts.input ?? opts.ctx.user?.name ?? 'world'}`),
|
|
72
|
+
// checked in resolver
|
|
73
|
+
secret: t.procedure.query((opts) => {
|
|
74
|
+
if (!opts.ctx.user) {
|
|
75
|
+
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
secret: 'sauce',
|
|
79
|
+
};
|
|
80
|
+
}),
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Option 2: Authorize using middleware
|
|
85
|
+
|
|
86
|
+
```ts no-check title="server/routers/_app.ts"
|
|
87
|
+
import { initTRPC, TRPCError } from '@trpc/server';
|
|
88
|
+
import { z } from 'zod';
|
|
89
|
+
|
|
90
|
+
type Context = { user: { name: string } | null };
|
|
91
|
+
|
|
92
|
+
export const t = initTRPC.context<Context>().create();
|
|
93
|
+
|
|
94
|
+
// you can reuse this for any procedure
|
|
50
95
|
export const protectedProcedure = t.procedure.use(
|
|
51
96
|
async function isAuthed(opts) {
|
|
52
97
|
const { ctx } = opts;
|
|
98
|
+
// `ctx.user` is nullable
|
|
53
99
|
if (!ctx.user) {
|
|
54
100
|
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
|
55
101
|
}
|
|
102
|
+
|
|
56
103
|
return opts.next({
|
|
57
104
|
ctx: {
|
|
58
|
-
|
|
105
|
+
// ✅ user value is known to be non-null now
|
|
106
|
+
user: ctx.user,
|
|
59
107
|
},
|
|
60
108
|
});
|
|
61
109
|
},
|
|
62
110
|
);
|
|
63
111
|
|
|
64
|
-
|
|
112
|
+
t.router({
|
|
113
|
+
// this is accessible for everyone
|
|
114
|
+
hello: t.procedure
|
|
115
|
+
.input(z.string().nullish())
|
|
116
|
+
.query((opts) => `hello ${opts.input ?? opts.ctx.user?.name ?? 'world'}`),
|
|
117
|
+
admin: t.router({
|
|
118
|
+
// this is accessible only to admins
|
|
119
|
+
secret: protectedProcedure.query((opts) => {
|
|
120
|
+
return {
|
|
121
|
+
secret: 'sauce',
|
|
122
|
+
};
|
|
123
|
+
}),
|
|
124
|
+
}),
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Building on a protected procedure
|
|
129
|
+
|
|
130
|
+
Since a procedure's middlewares run in order, you can add more checks on top of `protectedProcedure`, where `ctx.user` is already non-null:
|
|
131
|
+
|
|
132
|
+
```ts no-check title="server/trpc.ts"
|
|
133
|
+
import { initTRPC, TRPCError } from '@trpc/server';
|
|
134
|
+
|
|
135
|
+
type Context = { user: { name: string; role: 'admin' | 'user' } | null };
|
|
136
|
+
|
|
137
|
+
export const t = initTRPC.context<Context>().create();
|
|
138
|
+
|
|
139
|
+
export const protectedProcedure = t.procedure.use(async (opts) => {
|
|
140
|
+
if (!opts.ctx.user) {
|
|
141
|
+
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
|
142
|
+
}
|
|
143
|
+
return opts.next({ ctx: { user: opts.ctx.user } });
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
export const adminProcedure = protectedProcedure.use(async (opts) => {
|
|
147
|
+
if (opts.ctx.user.role !== 'admin') {
|
|
148
|
+
throw new TRPCError({ code: 'FORBIDDEN' });
|
|
149
|
+
}
|
|
150
|
+
return opts.next();
|
|
151
|
+
});
|
|
65
152
|
```
|
|
66
153
|
|
|
67
|
-
|
|
68
|
-
|
|
154
|
+
Throw `UNAUTHORIZED` (401) when the caller isn't signed in, and `FORBIDDEN` (403) when they are, but aren't allowed to do this.
|
|
155
|
+
|
|
156
|
+
## Sending credentials from the client
|
|
157
|
+
|
|
158
|
+
- **Cookies** are sent with every request when the client and server are on the same origin. For another origin, see [CORS & Cookies](https://trpc.io/docs/client/cors).
|
|
159
|
+
- **Headers** like `Authorization` can be set on any HTTP link with the [`headers`](https://trpc.io/docs/client/headers) option.
|
|
160
|
+
- **Subscriptions** over SSE can't send custom headers with the browser's `EventSource`. See [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink#headers-and-authorization--authentication) for the options.
|
|
161
|
+
- **WebSockets** send [connection params](https://trpc.io/docs/server/websockets#connectionParams) when the connection opens, which `createContext` reads from `opts.info.connectionParams`.
|
|
162
|
+
|
|
163
|
+
## Common mistakes
|
|
164
|
+
|
|
165
|
+
- **Calling `opts.next()` without the narrowed `ctx`.** Procedures after the middleware still see `ctx.user` as nullable. Pass `opts.next({ ctx: { user: opts.ctx.user } })`, as in [Option 2](https://trpc.io/docs/server/authorization#option-2-authorize-using-middleware).
|
|
166
|
+
- **Throwing in `createContext` for a missing or invalid token.** That fails every procedure in the request, public ones too. Return `user: null` instead, and let a middleware reject the procedures that need a user.
|
|
167
|
+
- **Putting tokens in `httpSubscriptionLink`'s `connectionParams`.** They are sent in the URL, where servers and proxies may log them. Prefer cookies, or headers through an `EventSource` ponyfill.
|
|
168
|
+
|
|
169
|
+
## Headers
|
|
170
|
+
|
|
171
|
+
From https://trpc.io/docs/client/headers
|
|
172
|
+
|
|
173
|
+
The headers option may be used with any of our HTTP links: [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink), [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink), [`httpLink`](https://trpc.io/docs/client/links/httpLink), or [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink).
|
|
174
|
+
|
|
175
|
+
`headers` can be both an object or a function. If it's a function it will get called dynamically for every HTTP request.
|
|
176
|
+
|
|
177
|
+
```ts no-check title="utils/trpc.ts"
|
|
69
178
|
import { createTRPCClient, httpBatchLink } from '@trpc/client';
|
|
70
|
-
import type { AppRouter } from '
|
|
179
|
+
import type { AppRouter } from './server';
|
|
71
180
|
|
|
72
|
-
let token
|
|
73
|
-
|
|
74
|
-
|
|
181
|
+
let token: string;
|
|
182
|
+
|
|
183
|
+
export function setToken(newToken: string) {
|
|
184
|
+
/**
|
|
185
|
+
* You can also save the token to cookies, and initialize from
|
|
186
|
+
* cookies above.
|
|
187
|
+
*/
|
|
188
|
+
token = newToken;
|
|
75
189
|
}
|
|
76
190
|
|
|
77
191
|
export const trpc = createTRPCClient<AppRouter>({
|
|
78
192
|
links: [
|
|
79
193
|
httpBatchLink({
|
|
80
|
-
url: 'http://localhost:3000
|
|
194
|
+
url: 'http://localhost:3000',
|
|
195
|
+
/**
|
|
196
|
+
* Headers will be called on each request.
|
|
197
|
+
*/
|
|
81
198
|
headers() {
|
|
82
|
-
return {
|
|
199
|
+
return {
|
|
200
|
+
Authorization: token,
|
|
201
|
+
};
|
|
83
202
|
},
|
|
84
203
|
}),
|
|
85
204
|
],
|
|
86
205
|
});
|
|
87
206
|
```
|
|
88
207
|
|
|
89
|
-
|
|
208
|
+
### Example with auth login
|
|
90
209
|
|
|
91
|
-
|
|
210
|
+
```ts no-check title="auth.ts"
|
|
211
|
+
const result = await trpc.auth.login.mutate({ username: 'user', password: 'pass' });
|
|
212
|
+
setToken(result.accessToken);
|
|
213
|
+
```
|
|
92
214
|
|
|
93
|
-
|
|
94
|
-
|
|
215
|
+
The `token` can be whatever you want it to be. It's entirely up to you whether that's just a client-side
|
|
216
|
+
variable that you update the value of on success or whether you store the token and pull it from local storage.
|
|
95
217
|
|
|
96
|
-
|
|
97
|
-
const t = initTRPC.context<Context>().create();
|
|
218
|
+
## Headers and authorization / authentication
|
|
98
219
|
|
|
99
|
-
|
|
100
|
-
if (!ctx.user) {
|
|
101
|
-
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
|
102
|
-
}
|
|
103
|
-
return next({ ctx: { user: ctx.user } });
|
|
104
|
-
});
|
|
220
|
+
### Web apps
|
|
105
221
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
});
|
|
222
|
+
#### Same domain
|
|
223
|
+
|
|
224
|
+
If you're doing a web application, cookies are sent as part of the request as long as your client is on the same domain as the server.
|
|
225
|
+
|
|
226
|
+
#### Cross-domain
|
|
112
227
|
|
|
113
|
-
|
|
114
|
-
|
|
228
|
+
If the client and server are not on the same domain, you can use `withCredentials: true` ([read more on MDN here](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/withCredentials)).
|
|
229
|
+
|
|
230
|
+
**Example:**
|
|
231
|
+
|
|
232
|
+
```tsx no-check
|
|
233
|
+
// [...]
|
|
234
|
+
httpSubscriptionLink({
|
|
235
|
+
url: 'https://example.com/api/trpc',
|
|
236
|
+
eventSourceOptions() {
|
|
237
|
+
return {
|
|
238
|
+
withCredentials: true, // <---
|
|
239
|
+
};
|
|
240
|
+
},
|
|
241
|
+
});
|
|
115
242
|
```
|
|
116
243
|
|
|
117
|
-
###
|
|
244
|
+
### Custom headers through ponyfill
|
|
245
|
+
|
|
246
|
+
**Recommended for non-web environments**
|
|
247
|
+
|
|
248
|
+
You can ponyfill `EventSource` and use the `eventSourceOptions` -callback to populate headers.
|
|
118
249
|
|
|
119
|
-
```
|
|
250
|
+
```tsx no-check
|
|
120
251
|
import {
|
|
121
252
|
createTRPCClient,
|
|
122
253
|
httpBatchLink,
|
|
@@ -124,219 +255,213 @@ import {
|
|
|
124
255
|
splitLink,
|
|
125
256
|
} from '@trpc/client';
|
|
126
257
|
import { EventSourcePolyfill } from 'event-source-polyfill';
|
|
127
|
-
import type { AppRouter } from '
|
|
258
|
+
import type { AppRouter } from './server';
|
|
128
259
|
|
|
260
|
+
// Initialize the tRPC client
|
|
129
261
|
const trpc = createTRPCClient<AppRouter>({
|
|
130
262
|
links: [
|
|
131
263
|
splitLink({
|
|
132
264
|
condition: (op) => op.type === 'subscription',
|
|
133
265
|
true: httpSubscriptionLink({
|
|
134
|
-
url: 'http://localhost:3000
|
|
266
|
+
url: 'http://localhost:3000',
|
|
267
|
+
// ponyfill EventSource
|
|
135
268
|
EventSource: EventSourcePolyfill,
|
|
136
|
-
|
|
269
|
+
// options to pass to the EventSourcePolyfill constructor
|
|
270
|
+
eventSourceOptions: async ({ op }) => {
|
|
271
|
+
// ^ Includes the operation that's being executed
|
|
272
|
+
// you can use this to generate a signature for the operation
|
|
273
|
+
const signature = await getSignature(op);
|
|
137
274
|
return {
|
|
138
275
|
headers: {
|
|
139
|
-
authorization:
|
|
276
|
+
authorization: 'Bearer supersecret',
|
|
277
|
+
'x-signature': signature,
|
|
140
278
|
},
|
|
141
279
|
};
|
|
142
280
|
},
|
|
143
281
|
}),
|
|
144
282
|
false: httpBatchLink({
|
|
145
|
-
url: 'http://localhost:3000
|
|
146
|
-
headers() {
|
|
147
|
-
return { Authorization: `Bearer ${getToken()}` };
|
|
148
|
-
},
|
|
283
|
+
url: 'http://localhost:3000',
|
|
149
284
|
}),
|
|
150
285
|
}),
|
|
151
286
|
],
|
|
152
287
|
});
|
|
153
288
|
```
|
|
154
289
|
|
|
155
|
-
###
|
|
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
|
-
```
|
|
290
|
+
### Updating configuration on an active connection
|
|
167
291
|
|
|
168
|
-
|
|
169
|
-
// client/trpc.ts
|
|
170
|
-
import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
|
|
171
|
-
import type { AppRouter } from '../server/router';
|
|
292
|
+
`httpSubscriptionLink` leverages SSE through `EventSource`, ensuring that connections encountering errors like network failures or bad response codes are automatically retried. However, `EventSource` does not allow re-execution of the `eventSourceOptions()` or `url()` options to update its configuration, which is particularly important in scenarios where authentication has expired since the last connection.
|
|
172
293
|
|
|
173
|
-
|
|
174
|
-
url: 'ws://localhost:3001',
|
|
175
|
-
connectionParams: async () => ({
|
|
176
|
-
token: getToken(),
|
|
177
|
-
}),
|
|
178
|
-
});
|
|
294
|
+
To address this limitation, you can use a [`retryLink`](https://trpc.io/docs/client/links/retryLink) in conjunction with `httpSubscriptionLink`. This approach ensures that the connection is re-established with the latest configuration, including any updated authentication details.
|
|
179
295
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
});
|
|
183
|
-
```
|
|
296
|
+
> [!WARNING] Caution
|
|
297
|
+
> Please note that restarting the connection will result in the `EventSource` being recreated from scratch, which means any previously tracked events will be lost.
|
|
184
298
|
|
|
185
|
-
### SSE auth with cookies (same domain)
|
|
186
299
|
|
|
187
|
-
```
|
|
300
|
+
```tsx no-check
|
|
188
301
|
import {
|
|
189
302
|
createTRPCClient,
|
|
190
303
|
httpBatchLink,
|
|
191
304
|
httpSubscriptionLink,
|
|
305
|
+
retryLink,
|
|
192
306
|
splitLink,
|
|
193
307
|
} from '@trpc/client';
|
|
194
|
-
import
|
|
308
|
+
import {
|
|
309
|
+
EventSourcePolyfill,
|
|
310
|
+
EventSourcePolyfillInit,
|
|
311
|
+
} from 'event-source-polyfill';
|
|
312
|
+
import type { AppRouter } from './server';
|
|
195
313
|
|
|
314
|
+
// Initialize the tRPC client
|
|
196
315
|
const trpc = createTRPCClient<AppRouter>({
|
|
197
316
|
links: [
|
|
198
317
|
splitLink({
|
|
199
318
|
condition: (op) => op.type === 'subscription',
|
|
200
|
-
|
|
201
|
-
url: '
|
|
202
|
-
eventSourceOptions() {
|
|
203
|
-
return { withCredentials: true };
|
|
204
|
-
},
|
|
319
|
+
false: httpBatchLink({
|
|
320
|
+
url: 'http://localhost:3000',
|
|
205
321
|
}),
|
|
206
|
-
|
|
322
|
+
true: [
|
|
323
|
+
retryLink({
|
|
324
|
+
retry: (opts) => {
|
|
325
|
+
opts.op.type;
|
|
326
|
+
const code = opts.error.data?.code;
|
|
327
|
+
if (!code) {
|
|
328
|
+
// This shouldn't happen as our httpSubscriptionLink will automatically retry within when there's a non-parsable response
|
|
329
|
+
console.error('No error code found, retrying', opts);
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
if (code === 'UNAUTHORIZED' || code === 'FORBIDDEN') {
|
|
333
|
+
console.log('Retrying due to 401/403 error');
|
|
334
|
+
return true;
|
|
335
|
+
}
|
|
336
|
+
return false;
|
|
337
|
+
},
|
|
338
|
+
}),
|
|
339
|
+
httpSubscriptionLink({
|
|
340
|
+
url: async () => {
|
|
341
|
+
// calculate the latest URL if needed...
|
|
342
|
+
return getAuthenticatedUri();
|
|
343
|
+
},
|
|
344
|
+
// ponyfill EventSource
|
|
345
|
+
EventSource: EventSourcePolyfill,
|
|
346
|
+
eventSourceOptions: async () => {
|
|
347
|
+
// ...or maybe renew an access token
|
|
348
|
+
const token = await auth.getOrRenewToken();
|
|
349
|
+
|
|
350
|
+
return {
|
|
351
|
+
headers: {
|
|
352
|
+
authorization: `Bearer ${token}`,
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
},
|
|
356
|
+
}),
|
|
357
|
+
],
|
|
207
358
|
}),
|
|
208
359
|
],
|
|
209
360
|
});
|
|
210
361
|
```
|
|
211
362
|
|
|
212
|
-
|
|
363
|
+
### Connection params
|
|
213
364
|
|
|
214
|
-
|
|
365
|
+
In order to authenticate with `EventSource`, you can define `connectionParams` in `httpSubscriptionLink`. This will be sent as part of the URL, which is why other methods are preferred.
|
|
215
366
|
|
|
216
|
-
|
|
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.
|
|
367
|
+
```ts no-check title="server/context.ts"
|
|
368
|
+
import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
|
|
235
369
|
|
|
236
|
-
|
|
370
|
+
export const createContext = async (opts: CreateHTTPContextOptions) => {
|
|
371
|
+
const token = opts.info.connectionParams?.token;
|
|
237
372
|
|
|
238
|
-
|
|
373
|
+
// [... authenticate]
|
|
239
374
|
|
|
240
|
-
|
|
375
|
+
return {};
|
|
376
|
+
};
|
|
241
377
|
|
|
242
|
-
|
|
243
|
-
httpSubscriptionLink({
|
|
244
|
-
url: 'http://localhost:3000/trpc',
|
|
245
|
-
connectionParams: async () => ({
|
|
246
|
-
token: 'my-secret-jwt',
|
|
247
|
-
}),
|
|
248
|
-
});
|
|
378
|
+
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
249
379
|
```
|
|
250
380
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
381
|
+
```ts no-check title="client/trpc.ts"
|
|
382
|
+
import {
|
|
383
|
+
createTRPCClient,
|
|
384
|
+
httpBatchLink,
|
|
385
|
+
httpSubscriptionLink,
|
|
386
|
+
splitLink,
|
|
387
|
+
} from '@trpc/client';
|
|
388
|
+
import type { AppRouter } from './server';
|
|
255
389
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
390
|
+
// Initialize the tRPC client
|
|
391
|
+
const trpc = createTRPCClient<AppRouter>({
|
|
392
|
+
links: [
|
|
393
|
+
splitLink({
|
|
394
|
+
condition: (op) => op.type === 'subscription',
|
|
395
|
+
true: httpSubscriptionLink({
|
|
396
|
+
url: 'http://localhost:3000',
|
|
397
|
+
connectionParams: async () => {
|
|
398
|
+
// Will be serialized as part of the URL
|
|
399
|
+
return {
|
|
400
|
+
token: 'supersecret',
|
|
401
|
+
};
|
|
402
|
+
},
|
|
403
|
+
}),
|
|
404
|
+
false: httpBatchLink({
|
|
405
|
+
url: 'http://localhost:3000',
|
|
406
|
+
}),
|
|
407
|
+
}),
|
|
408
|
+
],
|
|
262
409
|
});
|
|
263
410
|
```
|
|
264
411
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
Source: www/docs/client/links/httpSubscriptionLink.md
|
|
412
|
+
From https://trpc.io/docs/client/links/httpSubscriptionLink#headers-and-authorization--authentication
|
|
268
413
|
|
|
269
|
-
|
|
414
|
+
## Authentication / connection params
|
|
270
415
|
|
|
271
|
-
|
|
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
|
-
```
|
|
416
|
+
> [!TIP]
|
|
417
|
+
> If you're doing a web application, you can ignore this section as the cookies are sent as part of the request.
|
|
282
418
|
|
|
283
|
-
Correct:
|
|
284
419
|
|
|
285
|
-
|
|
286
|
-
let cachedToken: string | null = null;
|
|
420
|
+
In order to authenticate with WebSockets, you can define `connectionParams` to `createWSClient`. This will be sent as the first message when the client establishes a WebSocket connection.
|
|
287
421
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
return cachedToken;
|
|
291
|
-
}
|
|
422
|
+
```ts no-check title="server/context.ts"
|
|
423
|
+
import type { CreateWSSContextFnOptions } from '@trpc/server/adapters/ws';
|
|
292
424
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
async headers() {
|
|
296
|
-
return { Authorization: `Bearer ${await ensureToken()}` };
|
|
297
|
-
},
|
|
298
|
-
});
|
|
299
|
-
```
|
|
425
|
+
export const createContext = async (opts: CreateWSSContextFnOptions) => {
|
|
426
|
+
const token = opts.info.connectionParams?.token;
|
|
300
427
|
|
|
301
|
-
|
|
428
|
+
// [... authenticate]
|
|
302
429
|
|
|
303
|
-
|
|
430
|
+
return {};
|
|
431
|
+
};
|
|
304
432
|
|
|
305
|
-
|
|
433
|
+
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
434
|
+
```
|
|
306
435
|
|
|
307
|
-
|
|
436
|
+
```ts no-check title="client/trpc.ts"
|
|
437
|
+
import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
|
|
438
|
+
import type { AppRouter } from './server';
|
|
439
|
+
import superjson from 'superjson';
|
|
308
440
|
|
|
309
|
-
|
|
310
|
-
|
|
441
|
+
const wsClient = createWSClient({
|
|
442
|
+
url: `ws://localhost:3000`,
|
|
311
443
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
444
|
+
connectionParams: async () => {
|
|
445
|
+
return {
|
|
446
|
+
token: 'supersecret',
|
|
447
|
+
};
|
|
448
|
+
},
|
|
449
|
+
});
|
|
450
|
+
export const trpc = createTRPCClient<AppRouter>({
|
|
451
|
+
links: [wsLink({ client: wsClient, transformer: superjson })],
|
|
452
|
+
});
|
|
319
453
|
```
|
|
320
454
|
|
|
321
|
-
|
|
455
|
+
`createContext` runs once per connection (after the connection params arrive, if you send them), and every call over that connection shares its result. If it throws, the server sends the error and closes the connection. A token is only checked when the connection opens, so it stays accepted on that connection after it expires.
|
|
322
456
|
|
|
323
|
-
|
|
324
|
-
import cors from 'cors';
|
|
325
|
-
|
|
326
|
-
createHTTPServer({
|
|
327
|
-
middleware: cors({ origin: 'https://myapp.com' }),
|
|
328
|
-
router: appRouter,
|
|
329
|
-
createContext,
|
|
330
|
-
}).listen(3000);
|
|
331
|
-
```
|
|
457
|
+
From https://trpc.io/docs/server/websockets#connectionParams
|
|
332
458
|
|
|
333
|
-
|
|
459
|
+
## References
|
|
334
460
|
|
|
335
|
-
|
|
461
|
+
- [Send cookies cross-origin](references/client-cors.md)
|
|
336
462
|
|
|
337
|
-
##
|
|
463
|
+
## Related skills
|
|
338
464
|
|
|
339
|
-
-
|
|
340
|
-
-
|
|
341
|
-
-
|
|
342
|
-
- **links** -- `splitLink`, `httpSubscriptionLink`, `wsLink` configuration
|
|
465
|
+
- `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
|
|
466
|
+
- `middlewares` (https://trpc.io/docs/server/middlewares): `npx @tanstack/intent@latest load @trpc/server#middlewares`
|
|
467
|
+
- `client-setup` (https://trpc.io/docs/client/vanilla/setup): `npx @tanstack/intent@latest load @trpc/client#client-setup`
|