Join us at San Diego API Security Summit 2024!
Join us at San Diego API Security Summit 2024!
Join us at San Diego API Security Summit 2024!
Join us at San Diego API Security Summit 2024!
Join us at San Diego API Security Summit 2024!
Join us at San Diego API Security Summit 2024!
Close
Privacy settings
We use cookies and similar technologies that are necessary to run the website. Additional cookies are only used with your consent. You can consent to our use of cookies by clicking on Agree. For more information on which data is collected and how it is shared with our partners please read our privacy and cookie policy: Cookie policy, Privacy policy
We use cookies to access, analyse and store information such as the characteristics of your device as well as certain personal data (IP addresses, navigation usage, geolocation data or unique identifiers). The processing of your data serves various purposes: Analytics cookies allow us to analyse our performance to offer you a better online experience and evaluate the efficiency of our campaigns. Personalisation cookies give you access to a customised experience of our website with usage-based offers and support. Finally, Advertising cookies are placed by third-party companies processing your data to create audiences lists to deliver targeted ads on social media and the internet. You may freely give, refuse or withdraw your consent at any time using the link provided at the bottom of each page.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
DevSecOps

tRPC Protocol

With growing API usage, grow the API exploitation and attack involving API. API seems a lucrative asset for hackers because its exploitation allows them to have great control over the concerned application and its related components.  

This is why it’s highly recommended to have a strong trust between the backend and frontend of the API development process. tRPC is one of the most commonly used API protocols. At Wallarm, we aim to educate API users about safe practices and procedures and this guide on tRPC protocol is one more step in that direction.

tRPC Protocol

What Is tRPC Protocol?

Let’s begin the guide by knowing the basic meaning of TypeScript Remote Procedure, or better call, tRPC protocol. For beginners, tRPC is one way to generate and use typesafe APIs in a way that no generation and schemas are part of the process. By far, this is the simplest and most lightweight library that we have for calling out the backend function to the client side from any remote location.  

The placement of the tRPC protocol permits both the backend & frontend teams to work in TypeScript.  

When the protocol is at work on the backend, it empowers the backend team so much that it can easily define the queries, generate mutations, and develop a unified type. At the frontend, tRPC acts like a factory only allowing a single type from the backend and engaged in Reach Query hooks that are further used for queries and mutations.

‍

What Is The Purpose Of tRPC?

One might want to learn about the significance of tRPC and why it should be used in the first place. Well, this section of the guide is going to discuss this topic. The main purpose of tRPC is to make the backend and frontend of an API well connected so that crucial data is transmitted smoothly.

As tRPC is a TypeScript-based library, it comes with a robust integration with IDE that is required for a seamless developer experience. It aims to simplify API calls by offering coding and schema-free development.

You can consider it as a viable means to eliminate complexities from the processes as it generates types automatically. Also, output and inputs are auto-validated.

‍

How Does tRPC Work?

As mentioned above, tRPC is very simple and is not dependent on schemas or codes to generate APIs. Hence, understanding its functionality is not difficult. For any frontend side communication to be started, procedures are required. As we all know, procedures are composable elements used to call backend data remotely.

Now, tRPC uses two procedures. The first procedure is a query that refers to the request that the client sent to the client to request specific data. Mutations are the second procedure of that gRPC protocol and it’s useful to update, delete, or create any backend data.

It’s highly recommended to use monorepo while tRPC is in place because it’s highly compatible with the protocol. If modern applications are under consideration, we will find that more than one repos are used to separate the backend and frontend.

When one decides not to work with monorepo with tRPC-type definitions, multiple errors are likely to occur.

‍

Is tRPC Better Than GraphQL?

In the developer community, tRPC vs GraphQL is a hot topic. As tRPC is often considered a lighter version of GraphQL, this comparison is obvious. For the backend of modern applications, these two are used in abundance and deliver a different set of perks.

For instance, tRPC is loved because of its speed and code-free usage while GraphQL is famous for its ability to integrate various kinds of data in one query. But, is it fair to do a direct tRPC v/s GraphQL comparison?

Honestly, this comparison is not ethical because both are entirely different things. GraphQL is a language for queries while tRPC is a library.

It’s better to refer to GraphQL as an HTTP transport layer that can be paired with any other transport layers and protocol that concludes GraphQL is a highly flexible resource. tRPC disappoints when it comes to flexibility as it mainly works with TypeScript and JavaScript. Even though multiple batteries and adaptors are offered, the default flexibility is limited.  

tRPC API is mainly used in the frontend and is responsible for seamless communication with the backend. When you have to make any API calls with the backend, you command tRPC and it does the job. Hence, it’s better to call tRPC an API’s ORM.

Now, let’s compare these two on the usability front. We have qualms to admit that it’s hard to bear tRPC when it comes to simplicity. It’s an easy-to-use tool compared to GraphQL or any other query language. This is because it doesn’t ask for any code generation. When you are involved in GraphQL API generation, you have to use codes and schema.

The process is lengthy and involves steps like defining schema, writing resolves for accurate data collection, and generating types using schema. The entire process is time and effort-consuming.

The best you can do to reduce efforts is to use a code-first GraphQL library that allows developers to write resolvers and extract the schema from them.

tRPC API generation is not at all dependent on code and schema generation. Developers can simply define the procedures, set up a server, and start communicating with the backend.

So, if simplicity is concerned, tRPC is better than GraphQL. But, this shouldn’t be the only criterion to conclude anything. Both are different resources with distinct characteristics. 

Deciding which one is better out of tRPC and GraphQL requires deeper digging on aspects like:

  • What kind of sources types are required

If your developer goals necessitate querying various data resources and decoupling services then GraphQL is the right choice to make. tRPC is preferred when decoupling of the backend and front is not required

  • Do you want to work with one language or combine many languages

If you want language freedom then it’s better to go with GraphQL as it can only grant you this freedom. tRPC is strict at this part and doesn’t get easily paired with any language. It will only work with TypeScript.

  • Is backend scaling on your mind

At times, developers have to scale the backend to meet the contemporary application requirements. If this is your goal, you had better go with GraphQL because it supports scalability. Application scalability is achieved with the help of schema that is in sync with both the backend and frontend. 

  • What are your development requirements

You need to sort out your development needs and label them as simple or complex. For simple requirements, go ahead and use tRPC as it’s easy, simple, and uncomplicated. There are no codes to hold back the development. tRPC keeps the fluff from APIs away and makes them as simple as possible.  

GraphQL can handle your complex requirements as there are codes, multiple language supports, and schemas.

Figure out all these things first and then pick a resource accordingly. Both these resources are quickly good in different scenarios. So, first, sort out what exactly you’re looking for, and then pick out tRPC and GraphQL. And in case you are interested in knowing about tRPC vs rest, then remember that unlike ts-rest, tRPC defines your API deployment in the form of a contract.

‍

tRPC vs gRPC

As both gRPC and tRPC are used for proffering safe typed APIs for servers or clients, they might seem the same to many. However, deeper analysis brings some viable differences on the surface. They both take a different approach to type-safe API calls.

For instance, gRPC is here to support type-safe API calls using the protobuf protocol. This compact wire protocol features protocol files that are later used to develop clients/servers.

With gRPC, you can work with languages like Python, Java, Go, and C++.

But, gRPC generates codes that are hard to read and debug. Also, codes need to be regenerated whenever schema changes, of any sort, are there. gRPC is not suitable to use in browser ecosystems as it’s tedious and heavyweight.

On the other hand, you have tRPC as a library for type-safe API calls. Unlike gPRC, tRPC is not wired. In fact, it uses HTTP. While gRPC codes are tough, tRPC is easy-to-process. As it only supports TypeScript, you don’t have the freedom to work with any language. 

tRPC doesn’t force you to generate codes to get started. You can type-safe API calls by simply generating the schemas and importing them to the clients or servers. It’s a web-native tool and uses JSON-RPC specifications.

‍

Benefits of tRPC

tRPC managed to gain sufficient attention from the developer community because it comes with laudable benefits such as:

  • Amazing straightforwardness

Being a very light library makes tRPC a very hands-on tool. You don’t have to do a lot of preparations to get started with tRPC. It keeps you away from the hassle of code generation and schema-handling. So, even a beginner can start with it.

As tRPC only fetches the types from the calls and keeps codes uninvolved in the API communication, making API calls is very simple with it. TypeScript, the foundation of tRPC, is itself a very simple language as it’s statically typed. So, making sense and getting hands-on experience is easy.

  • Increase the application’s speed

As this protocol checks the type definitions when compilation is going on, the application is a little more speedy and takes less time to respond.  

  • Support for monorepos

If you’re someone who loves using monorepos then you should try tRPC. This feature is useful when you aim to do effective version control and git history. For those who are using an outdated app version, because of any reason, tRPC will ensure that the frontend can query the appropriate backend version for the respective app.  

In absence of monorepo, working with the older version won’t be easy as the frontend will fail at querying the corresponding backend.  

  • Accelerating the development

If you need to develop APIs in a short period then tRPC is the best choice to make. tRPC cuts down the development time drastically by using type inference. Because of this, it’s easy to detect the relevant data automatically. Type inference will cut down the development time with this automatic data detection and makes required data easily available.

To accelerate the development a little more, the protocol allows developers to integrate seamlessly with all the leading IDEs. So, development becomes swift and smooth.

  • A wide range of batteries is included

tRPC comes with a carefully-designed library offering battery support for its adaptors for AWS Lambda, Fastify, Express, tRP React, Next.js, and many more.

  • Seamless integration of the backend and frontend of Next.js

If you’re working on a Next.js project then tRPC is the right tool to own. Seamlessly, it can integrate the backend and front of Next and simply the full-stack development.

‍

Disadvantages of tRPC

Despite the above-mentioned impressive outcomes, tRPC is not flawless. It has evident limitations that should be considered before you start using tRPC.

The main limitation or disadvantage of tRPC is that it restricts you with TypeScript. You can’t work with other languages or even collaborate with them to any extent. But, it’s compatible with all the leading JavaScript frameworks and can get easily paired with your ongoing JavaScript projects.

tRPC is capable of delivering the best when it’s used for small projects that are confined. Don’t expect it to deliver the same ease and robustness when you use it for extensive projects. If you still plan to use it for extensive projects, be ready to invest more effort.

Lastly, we would like to bring to your knowledge that you’re not allowed to do any customization for client queries. You’re tied up with the default functions that the server is offering to you. Along with queries, subscription customizations are also not supported.

How To Get Started

As mentioned above, getting started with tRPC is not rocket-science. It’s so simple that a novice developer can use it without any hassles. Here are the steps involved to use tRPC for your projects.

  1. Determine procedures

Start with defining the procedure for tRPC API development. As we all know, procedures refer to the functions required for API backend development. Characteristically, procedures are made of components and could be anything; a subscription, a mutation, or a query. Procedures exist in a bunch when they are used on routers.  

Mostly, the Zod validator is used for the procedure generation process. The role of this tool here is to make sure that the client’s input and procedure expectations are in sync with each other. As procedures are generated, you will receive a basic text string as a query result.

const t = initTRPC.create();
 
const router = t.router;
const publicProcedure = t.procedure;
 
const appRouter = router({
 greeting: publicProcedure
 .input(z.object({ name: z.string() }))
 .query((req) => {
 const { input } = req;
  
const input: {
 name: string;
}
 
 return {
 text: `Hello ${input.name}` as const,
 };
 }),
});
 
export type AppRouter = typeof appRouter;
  1. Create HTTP server

The next step is to create an HTTP server. For this, you will require appRouter. Use the below-mentioned command for HTTP server generation. 

const { listen } = createHTTPServer({
 router: appRouter,
});
// The API will keep an eye on port 3000 now!
listen(3000);

If everything is followed as instructed, there will be a fully-functional tRPC server running in no time. As tRPC API supports multiple routers, it will be easy to work with tRPC React, Fetch API, Node HTTP and many other servers. 

  1. Connect your client and make requests

Once you have a functional server by your side, you’re now all set to develop a client and continue data querying. 

const trpc = createTRPCProxyClient<AppRouter>({
 links: [
 httpBatchLink({
 url: 'http://localhost:3000/trpc',
 }),
 ],
});
const res = await trpc.greeting.query({ name: 'John' }); 
const res: {
 text: `Hello ${string}`;
}

In this sample code, AppRouter type was passed during client creation so that we have TypeScript autocomplete and Intellisense well-synced with backend API. The entire process remains code-free. 

That’s it! You now have a functional tRPC API ready by your side. 

‍

Conclusion 

As the guide ends, we have clarity on tRPC and how it works. We learned that this protocol is an easy way to type-safe an API without being engaged in coding and schema. Developers stand a chance to develop a functional API in less time as no coding is involved. It’s easy to learn and perfect for beginners. 

However, the guide made one thing clear you’ve to stick to TypeScript if you go with tRPC. Also, this is perfect only for small projects. What does your experience with tRPC say? Are you convinced with its offerings or would like to see considerable changes? Do share your feedback with us.

FAQ

Open
Is tRPC related to gRPC?
Open
What is tRPC vs REST?
Open
What is tRPC used for?

References

Subscribe for the latest news

Updated:
November 12, 2024
Learning Objectives
Subscribe for
the latest news
subscribe
Related Topics