Headers
The headers option may be used with any of our HTTP links: httpBatchLink, httpBatchStreamLink, httpLink, or httpSubscriptionLink.
headers can be both an object or a function. If it's a function it will get called dynamically for every HTTP request.
utils/trpc.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';lettoken : string;export functionsetToken (newToken : string) {/*** You can also save the token to cookies, and initialize from* cookies above.*/token =newToken ;}export consttrpc =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000',/*** Headers will be called on each request.*/headers () {return {Authorization :token ,};},}),],});
utils/trpc.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';lettoken : string;export functionsetToken (newToken : string) {/*** You can also save the token to cookies, and initialize from* cookies above.*/token =newToken ;}export consttrpc =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000',/*** Headers will be called on each request.*/headers () {return {Authorization :token ,};},}),],});
Example with auth login
auth.tstsconstresult = awaittrpc .auth .login .mutate ({username : 'user',password : 'pass' });setToken (result .accessToken );
auth.tstsconstresult = awaittrpc .auth .login .mutate ({username : 'user',password : 'pass' });setToken (result .accessToken );
The token can be whatever you want it to be. It's entirely up to you whether that's just a client-side
variable that you update the value of on success or whether you store the token and pull it from local storage.