tRPC: What the future of the backend looks like

trpc:-what-the-future-of-the-backend-looks-like

A new way of communicating between frontends and backends has arrived in our developer lives, aiming to make things simpler and faster.

This technology I’m talking about is tRPC, which is a library that facilitates the creation of APIs between the client and the server.

What is tRPC?

tRPC is based on the concept of RPC (Remote Procedure Call) but is specifically designed to be used with TypeScript in modern web environments.

By using tRPC, you can define your APIs on the server using TypeScript. This allows you to specify data types and ensure that the data sent and received is correct.

On the client side, you can also leverage TypeScript to obtain strong type checking in API calls, which builds robust and reliable communication.

// BackEnd
const appRouter = router({
  userList: publicProcedure.query(async () => {
    const users = [{ name: 'david' }, { name: 'andres' }];
    return users;
  }),
});

// FrontEnd
const users = await trpc.userList.query();
console.log(users); // => [{ name: 'david' }, { name: 'andres' }]

¿How does tRPC work? / ¿How is it possible?

We can describe the functioning of tRPC as an eight-step process.

  1. API Definition on the Server:
    First, the API is defined on the server using tRPC. This involves creating functions and methods that can be remotely called by clients. Each function is defined with its name, input parameters, and the expected data type to be returned.

  2. Generation of TypeScript Code:
    tRPC uses this API definition on the server to automatically generate TypeScript code that represents the API functions. These generated functions will be used by the client to make API calls.

  3. Client Installation:
    On the client side (such as a web application), the tRPC client is installed. This involves installing @trpc/client or a library provided by the community. This library provides the generated functions that correspond to the API defined on the server.

  4. API Calls on the Client:
    On the client, you can directly call the functions generated by tRPC as if they were local functions. These calls can be made synchronously or asynchronously, depending on your preferred way of handling them.

  5. Serialization and Data Sending:
    When a tRPC function call is made on the client, the data and parameters are serialized (converted into a suitable format for transfer) and sent to the server through an HTTP/1.1 or HTTP/2 request.

  6. Execution on the Server:
    On the server, tRPC deserializes the received data, identifies the corresponding function based on the call name and parameters, and executes the function.

  7. Response Processing:
    After executing the function on the server, a response is generated that may include the requested results or data. This response is serialized and sent back to the client.

  8. Reception and Usage by the Client:
    On the client, the response is deserialized and delivered to the function on the client that initiated the original call. The data or results can be used in the client’s code as needed.

Describing how does tRPC work

What’s the difference between tRPC and gRPC?

tRPC and gRPC are two different technologies, although they share similarities in their names due to their relationship with RPC. Here are some key differences between tRPC and gRPC:

  1. Programming language and platform:

    • tRPC: It’s specifically designed to work with TypeScript and is most commonly used in the context of web applications based on JavaScript/TypeScript.
    • gRPC: It’s designed to be cross-platform and supports multiple programming languages, including C++, Java, Python, Go, and more. It’s commonly used in microservices architectures and broader distributed applications.
  2. Communication Protocol:

    • tRPC: It uses HTTP/1.1 or HTTP/2 as the communication protocol. It can send data in JSON or binary format, making it suitable for modern web environments.
    • gRPC: It uses HTTP/2 as the communication protocol, and the default data serialization format is Protocol Buffers (protobuf), which is more efficient and compact than JSON. This makes it more suitable for high-traffic and performance-intensive applications.
  3. Flexibility and Ease of Use:

    • tRPC: It’s designed with a simple syntax and structure, making it easy to use and quick to set up for small to medium-sized projects. It’s lightweight and can be suitable for cases where quick setup is desired.
    • gRPC: It has a more complex syntax due to the use of protocol buffers and requires more initial setup. It’s more powerful in larger and more complex scenarios, such as distributed systems and microservice architectures.

Why Should Someone Use tRPC?

There are several reasons why someone might consider using tRPC in their TypeScript web projects:

  1. Ease of Use:
    tRPC is designed with a simple and easily understandable syntax, making implementation and usage straightforward. It doesn’t require a steep learning curve, making it ideal for small to medium-sized projects.

  2. TypeScript-Friendly:
    Being TypeScript-specific, tRPC allows you to define data types both on the server and the client, providing greater safety and helping to avoid common data type-related errors.

  3. Transparent Communication:
    tRPC facilitates communication between the client and server, abstracting much of the underlying logic and enabling API calls to be made transparently as if they were local functions.

  4. Lightweight Approach:
    tRPC is designed to be a lightweight and agile solution, making it suitable for smaller projects or when a quick setup without complications is needed.

  5. Modern Web Technology Compatibility:
    By using HTTP/1.1 or HTTP/2 and allowing data to be sent in JSON or binary format, tRPC is compatible with modern web technologies, allowing easy integration into existing web applications.

  6. Documentation and Active Community:
    tRPC comes with solid documentation and an active community of users and developers, which can facilitate the learning process and provide additional support for any questions or issues.

  7. Scalability:
    While tRPC is more suitable for small to medium-sized projects, it can be scalable as your application grows. It’s possible to migrate to more complex RPC solutions like gRPC if the project reaches a higher level of complexity.

Ultimately, the choice to use tRPC will depend on the specific needs of your project and the context you’re in. If you’re looking for a simple, quickly implementable solution focused on TypeScript to facilitate communication between the client and server, tRPC can be a suitable option.
And if you would like to start testing technology, I will share the following links for you to discover the ecosystem:

Thanks for reading

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
react-custom-hook:-useeffectonce

React Custom Hook: useEffectOnce

Next Post
nhan-dinh-ket-qua-bong-da-hom-nay

NHẬN ĐỊNH KẾT QUẢ BÓNG ĐÁ HÔM NAY

Related Posts

「設計ミス」の社会を再編する:AIと共創する未来の働き方とシステム思考

こんにちは、Soraです。この記事をお読みいただき、ありがとうございます。突然ですが、少しだけ想像してみてください。朝、もう少しだけ布団の温もりを感じていたいのに、「仕事だから」と自分にムチを打って起き上がる。満員電車に身体を押し込まれ、会社に着けば成果を求められ、同僚のフォローに追われる。気づけば形式だけの会議が続き、帰宅する頃には自分のための時間はほとんど残っていない…。もし、こうした日々に少しでも心当たりがあるなら、ふと胸の奥で「このままで、本当にいいのだろうか?」という静かな声が聞こえることがあるのではないでしょうか。本稿では、その胸のざわめきを「個人の怠け」や「甘え」として片付けるのではなく、私たちを取り巻く社会そのものの「設計ミス」のシグナルとして捉え直すことを提案します。そして、その設計をどうすれば再編できるのか、具体的なデータも交えながら、皆さんと一緒に考えていきたいと思います。### 第一章|「労働=価値」という虚構の検証私たちはいつの間にか、「働くことが人間の価値を決める」という前提を内面化しています。しかし、この考え方は本当に自明なのでしょうか。いくつかのデータは、この前提が現代において大きな歪みを生んでいる可能性を示唆しています。 **異常に低い仕事への熱意:米ギャラップ社の調査によると、日本の「熱意あふれる社員」の割合はわずか5%。これは調査した139カ国中、最下位レベルです。多くの人が、仕事に対してポジティブな感情を持てずにいる現状が伺えます。* 構造的な高ストレス状態:厚生労働省の調査では、仕事で強いストレスを感じている労働者の割合は、常に半数を超えています。これは個人の精神的な強さの問題ではなく、労働環境そのものに構造的な問題が潜んでいることの現れです。* 先進国で低位の労働生産性:日本の時間当たり労働生産性は、OECD加盟38カ国中30位(2022年)と、長年低い水準にあります。長時間働き、高いストレスを感じているにもかかわらず、それが必ずしも高い成果に結びついていないのです。これらの事実は、「個人の努力が足りない」からではなく、「努力の方向性を規定する社会の設計そのもの」に無理が生じていることを示しているのではないでしょうか。### 第二章|人生を“準備期間”にしてしまうプログラム私たちの多くは、無意識のうちに次のような人生のレールに乗せられています。 **学生時代:より良い大学に入るための「準備」* 大学時代:より良い会社に入るための「準備」* 社会人時代:昇進や老後のための「準備」* 老後:人生の終わりを迎えるための「準備」人生が常に何かの「準備」の連続で、「今、この瞬間を生きる」ことが後回しにされてしまう。この構造を支えているのが、「安定こそが正義」「みんなと同じが安心」といった、思考停止を促す“プログラム”です。このプログラムは、私たちの感性を少しずつ麻痺させ、構造への疑問を抱かせないように作用します。**### 第三章|思考のOSを更新する「言語の再設計」社会のプログラムから抜け出し、自分自身の思考を取り戻す第一歩は、言葉を意識的に変えることです。固定観念を強化する言葉を、私は「毒語」と呼んでいます。この毒語を、本質を捉えた「対抗語彙」に置き換えることで、世界の見え方は大きく変わります。| 毒語(思考停止を招く言葉) | 対抗語彙(本質を捉える言葉) | 置き換えの狙い || :—…
Read More