Skip to main content
Version: 10.x

自定义标头

使用 httpBatchLinkhttpLink 时,可以在配置中自定义标头选项。

¥The headers option can be customized in the config when using the httpBatchLink or the httpLink.

headers 既可以是对象也可以是函数。如果它是一个函数,它将针对每个 HTTP 请求动态调用。

¥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.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,
};
},
}),
],
};
},
});

身份验证登录示例

¥Example with auth login

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 可以是你想要的任何东西。这完全取决于你是否只是一个在成功时更新其值的客户端变量,或者是否存储令牌并从本地存储中提取它。

¥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.