メインコンテンツへスキップ
バージョン: 11.x

カスタムヘッダー

httpBatchLinkまたは httpLinkを使用するとき、headersオプションを config でカスタマイズできます。

headers はオブジェクトまたは関数のどちらでもかまいません。関数の場合は、すべての HTTP リクエストに対して動的に呼び出されます。

utils/trpc.ts
ts
// Import the router type from your server file
import 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.ts
ts
// Import the router type from your server file
import 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.tsx
ts
const loginMut = trpc.auth.login.useMutation({
onSuccess(opts) {
token = opts.accessToken;
},
});
pages/auth.tsx
ts
const loginMut = trpc.auth.login.useMutation({
onSuccess(opts) {
token = opts.accessToken;
},
});

token は何でもかまいません。成功時にクライアント側の変数として値を更新するか、トークンを保存してローカルストレージから取得するかは、完全にあなた次第です。