Skip to main content

Creating a tRPC API Route

Ok So first - what is tRPC and what problem does it solve about NextJS. As per the website

tRPC allows you to easily build & consume fully typesafe APIs without schemas or code generation

Basically, if we fetch data from an api endpoint, we usually do not know the shape of the data we are receiving, and therefore the data we receive is usually not type safe

tRPC solves this! For monolithic applications (when the server and client are on the same codebase) - we can create type-safe APIs

For most of our complicated routes - we use tRPC.

Example tRPC use in place.ts

In this image, we can see that a complex data structure is being returned. It would be extremely annoying to redefine such a data structure later on. Instead, tRPC does this for us

info

tRPC uses tanstack query under the hood for route fetching. I highly recommend Tanstack query - it allows fetching to be done as a stateful hook which abstracts a lot of the asynchronous logic and exposes a really react principles friendly interface

Tanstack Query

honestly if i was creating a new application - i would heavily look into the tanstack associated tools - they are really well made