Setting up tRPC
Installation
In order to set up tRPC in your project, you need to add the following dependencies to your project:
Setting up tRPC in your project
There are two folders of note when it comes to tRPC in your project. These are:
server/: This folder contains the tRPC API routes. You will primarily work here to define your API procedures and handle requests.
trpc/: This folder is for tRPC configuration, including the setup of routers and context. Changes here are less frequent unless you're adding new procedures or modifying the configuration.
app/layout.tsx: In order to use tRPC in your project, you will need to add the TRPCReactProvider to your project. This is done in the app/layout.tsx
file.
app/api/trpc/[trpc]route.ts: This file is the entry point for tRPC. It is used to create the tRPC router and handle requests.
This file uses a local env.js file to store your environment variables. So make sure to add that in your project. Here is an example of what the env file should look like.
Creating a tRPC Router
tRPC shines by enabling you to create a router that links your frontend and backend effortlessly. When you change props or types between the two, those updates are automatically reflected in the router. This feature accelerates your development cycles.
This router is essential for managing all your API requests. You can find the router.ts
file in the trpc/
folder. This is where you'll define your API procedures.