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

tRPC 클라이언트 설정

비공식 베타 번역

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

1. tRPC 클라이언트 라이브러리 설치​

선호하는 패키지 매니저를 사용해 @trpc/client 라이브러리를 설치하고, 필요한 타입을 포함하는 @trpc/server도 함께 설치하세요.

bash
npm install @trpc/client @trpc/server
bash
npm install @trpc/client @trpc/server

2. App Router 가져오기​

비공식 베타 번역

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

클라이언트 애플리케이션에 AppRouter 타입을 가져옵니다. 이 타입은 전체 API의 구조를 담고 있습니다.

ts
import type { AppRouter } from '../server/router';
ts
import type { AppRouter } from '../server/router';
팁

import type을 사용하면 컴파일 시점에 참조가 제거되어 실수로 서버 측 코드를 클라이언트로 가져오는 것을 방지할 수 있습니다. 자세한 내용은 TypeScript 문서를 참조하세요.

3. tRPC 클라이언트 초기화​

createTRPCProxyClient 메서드를 사용해 tRPC 클라이언트를 생성하고, API를 가리키는 종료 링크가 포함된 links 배열을 추가하세요. tRPC 링크에 대해 자세히 알아보려면 여기를 클릭하세요.

client.ts
ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../path/to/server/trpc';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000/trpc',
// You can pass any HTTP headers you wish here
async headers() {
return {
authorization: getAuthCookie(),
};
},
}),
],
});
client.ts
ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../path/to/server/trpc';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000/trpc',
// You can pass any HTTP headers you wish here
async headers() {
return {
authorization: getAuthCookie(),
};
},
}),
],
});

4. tRPC 클라이언트 사용하기​

내부적으로 이는 타입이 지정된 JavaScript Proxy를 생성하여 완전한 타입 안정성(type-safe) 방식으로 tRPC API와 상호작용할 수 있게 합니다:

client.ts
ts
const bilbo = await client.getUser.query('id_bilbo');
// => { id: 'id_bilbo', name: 'Bilbo' };
const frodo = await client.createUser.mutate({ name: 'Frodo' });
// => { id: 'id_frodo', name: 'Frodo' };
client.ts
ts
const bilbo = await client.getUser.query('id_bilbo');
// => { id: 'id_bilbo', name: 'Bilbo' };
const frodo = await client.createUser.mutate({ name: 'Frodo' });
// => { id: 'id_frodo', name: 'Frodo' };

모든 준비가 완료되었습니다!