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

커스텀 헤더

비공식 베타 번역

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

headers 옵션은 nextjs에서 withTRPC를 사용하거나 react.js에서 createClient를 사용할 때 config에서 커스터마이즈할 수 있습니다.

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