SST로 Cloudflare에 tRPC 배포하기
SST를 사용해 Cloudflare에 tRPC API를 생성하고 배포합니다.
Cloudflare에서 SST를 사용한 tRPC 구축
tRPC API와 간단한 클라이언트를 만들고, 이를 SST를 사용해 Cloudflare에 배포해 보겠습니다.
시작하기 전에 Cloudflare API 토큰을 생성하세요.
1. 프로젝트 생성
앱을 만들어 보겠습니다.
mkdir my-trpc-app && cd my-trpc-appnpm init -ySST 초기화
이제 앱에서 SST를 초기화해 보겠습니다.
npx sst@latest initnpm install기본값을 선택하고 Cloudflare를 선택합니다. 이렇게 하면 프로젝트 루트에 sst.config.ts 파일이 생성됩니다.
Cloudflare API 토큰 설정하기
Cloudflare API 토큰은 .env 파일에 저장하거나 직접 설정할 수 있습니다.
export CLOUDFLARE_API_TOKEN=aaaaaaaa_aaaaaaaaaaaa_aaaaaaaaexport CLOUDFLARE_DEFAULT_ACCOUNT_ID=aaaaaaaa_aaaaaaaaaaaa_aaaaaaaa2. API 추가하기
tRPC 서버용 워커와 클라이언트용 워커를 추가해 보겠습니다. sst.config.ts 파일을 업데이트합니다.
async run() { const trpc = new sst.cloudflare.Worker("Trpc", { url: true, handler: "index.ts", });
const client = new sst.cloudflare.Worker("Client", { url: true, link: [trpc], handler: "client.ts", });
return { api: trpc.url, client: client.url, };}서버를 클라이언트에 연결합니다. 이를 통해 클라이언트에서 서버에 접근할 수 있습니다.
3. 서버 생성하기
tRPC 서버를 만들어 보겠습니다. index.ts에 다음 코드를 추가합니다.
const t = initTRPC.context().create();
const router = t.router({ greet: t.procedure .input(z.object({ name: z.string() })) .query(({ input }) => { return `Hello ${input.name}!`; }),});
export type Router = typeof router;
export default { async fetch(request: Request): Promise<Response> { return fetchRequestHandler({ router, req: request, endpoint: "/", createContext: (opts) => opts, }); },};여기서는 _문자열_을 입력으로 받는 greet라는 간단한 메서드를 생성합니다.
필요한 import 문을 추가합니다.
import { z } from "zod";import { initTRPC } from "@trpc/server";import { fetchRequestHandler } from "@trpc/server/adapters/fetch";그리고 npm 패키지를 설치합니다.
npm install zod @trpc/server@next4. 클라이언트 추가
이제 클라이언트에서 서버에 연결해 보겠습니다. client.ts에 다음 내용을 추가합니다.
export default { async fetch() { const client = createTRPCClient<Router>({ links: [ httpBatchLink({ url: "http://localhost/", fetch(req) { return Resource.Trpc.fetch(req); }, }), ], }); return new Response( await client.greet.query({ name: "Patrick Star", }), ); },};필요한 모듈을 가져옵니다. API의 _타입_을 가져오는 것에 주목하세요.
import { Resource } from "sst";import type { Router } from "./index";import { createTRPCClient, httpBatchLink } from "@trpc/client";클라이언트 npm 패키지를 설치합니다.
npm install @trpc/client@next개발 모드 시작
여러분의 앱을 개발 모드로 시작합니다.
npx sst dev이 명령어를 실행하면 두 개의 URL이 제공됩니다.
+ 완료 api: https://my-trpc-app-jayair-trpcscript.sst-15d.workers.dev client: https://my-trpc-app-jayair-clientscript.sst-15d.workers.dev앱 테스트하기
앱을 테스트하려면 클라이언트 URL에 접속하세요.
curl https://my-trpc-app-jayair-clientscript.sst-15d.workers.dev이 명령어를 실행하면 Hello Patrick Star!가 출력됩니다.
5. 앱 배포하기
이제 여러분의 앱을 배포해 보겠습니다.
npx sst deploy --stage production여기서는 어떤 스테이지 이름을 사용해도 되지만, 프로덕션을 위해 새로운 스테이지를 만드는 것이 좋습니다.