tRPC on Cloudflare with SST
Create and deploy a tRPC API in Cloudflare with SST.
We are going to build a tRPC API, a simple client, and deploy it to Cloudflare using SST.
Before you get started, make sure to Create your Cloudflare API token.
1. Create a project
Let’s start by creating our app.
Init SST
Now let’s initialize SST in our app.
Select the defaults and pick Cloudflare. This’ll create a sst.config.ts
file in your project root.
Set the Cloudflare API token
You can save your Cloudflare API token in a .env
file or just set it directly.
2. Add the API
Let’s add two Workers; one for our tRPC server and one that’ll be our client. Update your sst.config.ts
.
We are linking the server to our client. This will allow us to access the server in our client.
3. Create the server
Let’s create our tRPC server. Add the following to index.ts
.
We are creating a simple method called greet
that takes a string as an input.
Add the relevant imports.
And install the npm packages.
4. Add the client
Now we’ll connect to our server in our client. Add the following to client.ts
.
Add the imports. Notice we are importing the types for our API.
Install the client npm package.
Start dev mode
Start your app in dev mode.
This will give you two URLs.
Test your app
To test our app, hit the client URL.
This will print out Hello Patrick Star!
.
5. Deploy your app
Now let’s deploy your app.
You can use any stage name here but it’s good to create a new stage for production.