DEV Community

Cover image for tRPC in 100 seconds
Marcon
Marcon

Posted on

tRPC in 100 seconds

tRPC - A way to build entirely typesafe APIs without the need of schemas or code generation.

If you are building an API today, there are two main approaches: REST and GraphQL.

But there is actually another less talked about approach called tRPC with features like:

  • Autocompletion
  • Automatic typesafety
  • Request batching

In REST Land the most basic way to fetch data inside a React Application is to use the browser fetch api, when the browser first mounts in useEffect then manage the response in a useState. This approach does not have a strong contract between the frontend and the backend: for example if you decide to change the message property from greeting to text, typescript will not throw an error, but in our React Application we get a broken UI.

This is where tRPC comes in. To get started create a new project with npm create t3-app@latest.

tRPC is setup in routes and procedures, where a route is like a folder and a procedure is like a file.

If you open up the exampleRouter, you will see a hello procedure with an input object where name is a string, and an output object where greeting is a string.

To call the procedure in the frontend you have to use a special api object and navigate to the hello procedure by using the example router. Under the hood tRPC uses React Query to make the request

Note that changes to the backend will throw typescript errors in the frontend.

And additionally when making multiple requests, tRPC is going to batch all of them into a single HTTP Request.

There are a couple of instances where you shouldn't use tRPC:

  • When your frontend and backend code is not written in TypeScript
  • When you have separate backend and frontend teams

Here is the tRPC introduction in video form:

Top comments (0)