본문 바로가기
버전: 10.x

커스텀 헤더

비공식 베타 번역

이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →

httpBatchLinkhttpLink를 사용할 때 설정에서 헤더 옵션을 커스터마이징할 수 있습니다.

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(config) {
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(config) {
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은 원하는 어떤 형태든 가능합니다. 성공 시 값이 업데이트되는 클라이언트 측 변수로 사용하거나, 토큰을 저장한 후 로컬 스토리지에서 가져오는 방식 등 전적으로 개발자에게 달려 있습니다.