カスタムヘッダー
httpBatchLink
または httpLink
を使用するとき、headers
オプションを config でカスタマイズできます。
headers
はオブジェクトまたは関数のどちらでもかまいません。関数の場合は、すべての HTTP リクエストに対して動的に呼び出されます。
utils/trpc.tsts
// Import the router type from your server fileimport type { AppRouter } from '@/server/routers/app';import { httpBatchLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';let token: string;export function setToken(newToken: string) {/*** You can also save the token to cookies, and initialize from* cookies above.*/token = newToken;}export const trpc = createTRPCNext<AppRouter>({config(opts) {return {links: [httpBatchLink({url: 'http://localhost:3000/api/trpc',/*** Headers will be called on each request.*/headers() {return {Authorization: token,};},}),],};},});
utils/trpc.tsts
// Import the router type from your server fileimport type { AppRouter } from '@/server/routers/app';import { httpBatchLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';let token: string;export function setToken(newToken: string) {/*** You can also save the token to cookies, and initialize from* cookies above.*/token = newToken;}export const trpc = createTRPCNext<AppRouter>({config(opts) {return {links: [httpBatchLink({url: 'http://localhost:3000/api/trpc',/*** Headers will be called on each request.*/headers() {return {Authorization: token,};},}),],};},});
認証ログインを使用した例
pages/auth.tsxts
const loginMut = trpc.auth.login.useMutation({onSuccess(opts) {token = opts.accessToken;},});
pages/auth.tsxts
const loginMut = trpc.auth.login.useMutation({onSuccess(opts) {token = opts.accessToken;},});
token
は何でもかまいません。成功時にクライアント側の変数として値を更新するか、トークンを保存してローカルストレージから取得するかは、完全にあなた次第です。