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

헤더

비공식 베타 번역

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

헤더 옵션은 모든 HTTP 링크와 함께 사용할 수 있습니다: httpBatchLink, httpBatchStreamLink, httpLink, 또는 httpSubscriptionLink.

headers는 객체 또는 함수 형태로 지정할 수 있습니다. 함수로 지정할 경우 모든 HTTP 요청마다 동적으로 호출됩니다.

utils/trpc.ts
ts
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './server';
 
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 = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
/**
* Headers will be called on each request.
*/
headers() {
return {
Authorization: token,
};
},
}),
],
});
utils/trpc.ts
ts
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './server';
 
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 = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
/**
* Headers will be called on each request.
*/
headers() {
return {
Authorization: token,
};
},
}),
],
});

인증 로그인 예시

auth.ts
ts
const result = await trpc.auth.login.mutate({ username: 'user', password: 'pass' });
setToken(result.accessToken);
auth.ts
ts
const result = await trpc.auth.login.mutate({ username: 'user', password: 'pass' });
setToken(result.accessToken);

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