new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

tRPC · all subjects

client/headers

8 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

headers option with HTTP links

The headers option may be used with httpBatchLink, httpBatchStreamLink, httpLink, or httpSubscriptionLink.

headers as object or function

The headers option can be either an object or a function. If it is a function, it will be called dynamically for every HTTP request.

Dynamic headers function example

Example of setting headers dynamically on each request: ```ts import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from './server'; let token: string; export function setToken(newToken: string) { token = newToken; } export const trpc = createTRPCClient<AppRouter>({ links: [ httpBatchLink({ url: 'http://localhost:3000', headers() { return { Authorization: token, }; }, }), ], }); ``` This example shows storing a token in a variable and returning it from the headers function on each request.

Token storage options

The token can be stored as a client-side variable that is updated on success, or it can be stored in and retrieved from local storage or cookies.

Auth login flow example

Example of calling a login mutation and then setting the returned access token: ```ts const result = await trpc.auth.login.mutate({ username: 'user', password: 'pass' }); setToken(result.accessToken); ``` After receiving the access token from the login mutation, it can be stored for use in subsequent request headers.

headers option can be static or dynamic

The headers option in HTTPLinkOptions can either be a static HTTPHeaders object or a callback function that receives an object with an 'op' field containing the Operation and returns HTTPHeaders or a Promise<HTTPHeaders>.

Manual header forwarding in SSR

tRPC requires manual header forwarding during SSR instead of automatic forwarding to give developers control over which headers to include, avoiding potential header key collisions and allowing dynamic header modifications.

Forward cookie headers in SSR server links

In createTRPCNext config with ssr: true, the server-side httpBatchLink should include a headers function that returns { cookie: ctx.req.headers.cookie } if headers exist, else empty object.

Give your agent this brain