본문으로 건너뛰기
버전: 11.x

헤더

headers 옵션은 다음 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는 원하는 값으로 설정할 수 있습니다. 성공 시 값을 업데이트하는 클라이언트 측 변수인지, 아니면 토큰을 저장하고 로컬 스토리지에서 가져오는지는 전적으로 개발자의 선택에 달려 있습니다.