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

カスタムヘッダー

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

headersオプションは、Next.jsでwithTRPCを使用する場合やReact.jsでcreateClientを使用する場合に設定でカスタマイズ可能です。

headersはオブジェクトまたは関数のどちらでも指定可能です。関数を指定した場合、各HTTPリクエストのたびに動的に呼び出されます。

_app.tsx
ts
import type { AppRouter } from '@/server/routers/app';
import { withTRPC } from '@trpc/next';
import { AppType } from 'next/dist/shared/lib/utils';
export let token: string;
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
export default withTRPC<AppRouter>({
config(config) {
return {
links: [
httpBatchLink({
/** headers are called on every request */
headers: () => {
return {
Authorization: token,
};
},
}),
],
};
},
})(MyApp);
_app.tsx
ts
import type { AppRouter } from '@/server/routers/app';
import { withTRPC } from '@trpc/next';
import { AppType } from 'next/dist/shared/lib/utils';
export let token: string;
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
export default withTRPC<AppRouter>({
config(config) {
return {
links: [
httpBatchLink({
/** headers are called on every request */
headers: () => {
return {
Authorization: token,
};
},
}),
],
};
},
})(MyApp);

認証ログインの例

pages/auth.tsx
ts
const loginMut = trpc.useMutation(['auth.login'], {
onSuccess({ accessToken }) {
token = accessToken;
},
});
pages/auth.tsx
ts
const loginMut = trpc.useMutation(['auth.login'], {
onSuccess({ accessToken }) {
token = accessToken;
},
});

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