tRPC 클라이언트 설정
1. tRPC 클라이언트 라이브러리 설치
선호하는 패키지 매니저를 사용하여 @trpc/client 라이브러리를 설치하고, 필요한 타입을 포함하고 있는 @trpc/server도 함께 설치합니다.
- npm
- yarn
- pnpm
- bun
- deno
npm install @trpc/server @trpc/client
yarn add @trpc/server @trpc/client
pnpm add @trpc/server @trpc/client
bun add @trpc/server @trpc/client
deno add npm:@trpc/server npm:@trpc/client
AI 에이전트
AI 코딩 에이전트를 사용하는 경우, 더 나은 코드 생성을 위해 tRPC 스킬을 설치합니다:
bashnpx @tanstack/intent@latest install
bashnpx @tanstack/intent@latest install
2. 앱 라우터 가져오기
AppRouter 타입을 클라이언트 애플리케이션에 가져옵니다. 이 타입은 전체 API의 구조를 포함합니다.
utils/trpc.tstsimport type { AppRouter } from '../server/router';
utils/trpc.tstsimport type { AppRouter } from '../server/router';
팁
import type를 사용하면 참조가 컴파일 타임에 제거되므로, 서버 측 코드가 클라이언트에 의도치 않게 가져와지는 것을 방지할 수 있습니다. 자세한 내용은 TypeScript 문서를 참조하세요.
3. tRPC 클라이언트 초기화
createTRPCClient 메서드로 tRPC 클라이언트를 생성하고 API를 가리키는 종단 링크를 links 배열에 추가합니다. 자세한 내용은 tRPC 링크 문서를 참조하세요.
client.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000/trpc',// You can pass any HTTP headers you wish hereasyncheaders () {return {authorization :getAuthCookie (),};},}),],});
client.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000/trpc',// You can pass any HTTP headers you wish hereasyncheaders () {return {authorization :getAuthCookie (),};},}),],});
4. tRPC 클라이언트 사용
이 내부적으로 타입이 지정된 JavaScript Proxy를 생성하여, tRPC API를 완전히 타입 안전하게 상호작용할 수 있게 합니다:
client.tstsconstbilbo = awaitclient .getUser .query ('id_bilbo');// => { id: 'id_bilbo', name: 'Bilbo' };constfrodo = awaitclient .createUser .mutate ({name : 'Frodo' });// => { id: 'id_frodo', name: 'Frodo' };
client.tstsconstbilbo = awaitclient .getUser .query ('id_bilbo');// => { id: 'id_bilbo', name: 'Bilbo' };constfrodo = awaitclient .createUser .mutate ({name : 'Frodo' });// => { id: 'id_frodo', name: 'Frodo' };
모든 설정이 완료되었습니다!