Skip to content

SST를 사용하여 AWS에 tRPC 배포하기

SST를 사용하여 AWS에 tRPC API를 생성하고 배포합니다.

AWS에서 SST를 사용한 tRPC 구축

우리는 서버리스 tRPC API와 간단한 클라이언트를 구축하고, 이를 SST를 사용해 AWS에 배포할 것입니다.

시작하기 전에 AWS 자격 증명을 설정하세요.


1. 프로젝트 생성

앱을 만들어 보겠습니다.

Terminal window
mkdir my-trpc-app && cd my-trpc-app
npm init -y

SST 초기화

이제 앱에서 SST를 초기화해 보겠습니다.

Terminal window
npx sst@latest init
npm install

기본값을 선택하고 AWS를 선택합니다. 이렇게 하면 프로젝트 루트에 sst.config.ts 파일이 생성됩니다.


2. API 추가하기

tRPC 서버용과 클라이언트용으로 두 개의 Lambda 함수를 추가해 보겠습니다. sst.config.ts 파일을 업데이트하세요.

sst.config.ts
async run() {
const trpc = new sst.aws.Function("Trpc", {
url: true,
handler: "index.handler",
});
const client = new sst.aws.Function("Client", {
url: true,
link: [trpc],
handler: "client.handler",
});
return {
api: trpc.url,
client: client.url,
};
}

서버를 클라이언트에 연결했습니다. 이렇게 하면 클라이언트에서 서버의 URL에 접근할 수 있습니다.

개발 모드 시작

앱을 개발 모드로 실행합니다. 이 모드에서는 함수를 실시간으로 실행할 수 있습니다.

Terminal window
npx sst dev

이 명령어를 실행하면 두 개의 URL이 제공됩니다.

+ 완료
api: https://gyrork2ll35rsuml2yr4lifuqu0tsjft.lambda-url.us-east-1.on.aws
client: https://3x4y4kg5zv77jeroxsrnjzde3q0tgxib.lambda-url.us-east-1.on.aws

3. 서버 생성하기

tRPC 서버를 만들어 보겠습니다. index.ts에 다음 내용을 추가하세요.

index.ts
const t = initTRPC
.context<CreateAWSLambdaContextOptions<APIGatewayProxyEvent | APIGatewayProxyEventV2>>()
.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 const handler = awsLambdaRequestHandler({
router: router,
createContext: (opts) => opts,
});

여기서는 _문자열_을 입력으로 받는 간단한 greet 메서드를 만들었습니다.

필요한 모듈을 임포트하세요.

index.ts
import { z } from "zod";
import {
awsLambdaRequestHandler,
CreateAWSLambdaContextOptions
} from "@trpc/server/adapters/aws-lambda";
import { initTRPC } from "@trpc/server";
import { APIGatewayProxyEvent, APIGatewayProxyEventV2 } from "aws-lambda";

그리고 npm 패키지를 설치합니다.

Terminal window
npm install zod @trpc/server@next

4. 클라이언트 추가

이제 클라이언트에서 서버에 연결해 보겠습니다. client.ts에 다음 내용을 추가합니다.

client.ts
const client = createTRPCClient<Router>({
links: [
httpBatchLink({
url: Resource.Trpc.url,
}),
],
});
export async function handler() {
return {
statusCode: 200,
body: await client.greet.query({ name: "Patrick Star" }),
};
}

필요한 import를 추가합니다. API의 _타입_을 import하는 것에 주목하세요.

index.ts
import { Resource } from "sst";
import type { Router } from "./index";
import { createTRPCClient, httpBatchLink } from "@trpc/client";

클라이언트 npm 패키지를 설치합니다.

Terminal window
npm install @trpc/client@next

앱 테스트하기

앱을 테스트하려면 클라이언트 URL에 접속하세요.

Terminal window
curl https://3x4y4kg5zv77jeroxsrnjzde3q0tgxib.lambda-url.us-east-1.on.aws

이 명령어를 실행하면 Hello Patrick Star!가 출력됩니다.


5. 앱 배포하기

이제 여러분의 앱을 배포해 보겠습니다.

Terminal window
npx sst deploy --stage production

여기서는 어떤 스테이지 이름을 사용해도 되지만, 프로덕션을 위해 새로운 스테이지를 만드는 것이 좋습니다.


콘솔 연결하기

다음 단계로 SST 콘솔을 설정하여 앱을 _git push로 배포_하고 문제를 모니터링할 수 있습니다.

SST 콘솔 자동 배포

무료 계정을 생성하고 AWS 계정에 연결할 수 있습니다.