Get rid of your API schemas with tRPC

Rate this content
Bookmark
Slides

Do you know we can replace API schemas with a lightweight and type-safe library? With tRPC you can easily replace GraphQL or REST with inferred shapes without schemas or code generation. In this talk we will understand the benefit of tRPC and how apply it in a NextJs application. If you want reduce your project complexity you can't miss this talk.

This talk has been presented at React Day Berlin 2022, check out the latest edition of this React Conference.

FAQ

trPC is a library that simplifies the communication between client and server by eliminating the need for manually defining API schemas and generating TypeScript types. It is used to streamline development, especially in apps using TypeScript, by providing type safety and reducing code generation.

trPC does not require schema or type generation, unlike GraphQL and OpenAPI, which can lead to 'schema fatigue' due to constant updates and manual type generation. trPC offers a more streamlined approach, ideal for projects where type safety and rapid development are prioritized.

While trPC can be implemented in projects with separate front-end and back-end repositories, it loses some features like automatic refactoring. However, types from trPC can be encapsulated and reused across projects to maintain consistency.

trPC is better suited for microservices architectures rather than monolithic applications. It supports creating multiple services which can communicate with each other, leveraging trPC's capabilities for efficient service-to-service interactions.

trPC eliminates the need for code generation, ensuring type safety by default and improving collaboration between front-end and back-end teams. This leads to a more efficient development process and reduces potential errors from manual code entry.

trPC can be challenging in environments where multiple clients or versions are involved, as it might require creating separate procedures for each version or client. Traditional APIs like REST or GraphQL might be more suitable in these scenarios.

trPC can be used for public APIs but requires an additional library, such as trPC-openAPI, to handle documentation and public exposure. This library enables the use of decorators to generate OpenAPI documentation for trPC endpoints.

Giorgio Boa
Giorgio Boa
29 min
02 Dec, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's Talk introduces TRPC, a library that eliminates the need for code generation and provides type safety and better collaboration between front-end and back-end. TRPC is demonstrated in a Next JS application integrated with Prisma, allowing for easy implementation and interaction with the database. The library allows for seamless usage in the client, with automatic procedure renaming and the ability to call methods without generating types. TRPC's client-server interaction is based on HTTP requests and allows for easy debugging and tracing. The library also provides runtime type check and validation using Zod.

1. Introduction to API Schema with trPC

Short description:

Today we are talking about how to get rid of your API schema with trPC. There are two main ways to communicate from your server and client: open API and GraphQL. Open API requires learning a new specification, writing case-sensitive JSON or YAML, and generating schema and type script types. With GraphQL, you need to learn a new specification, generate type script types, and dump them into the client. I found a solution in TRPC, a popular library with over 100,000 weekly npm downloads and 60,000 stars on GitHub.

I'm so happy to be here. And today we are talking about how to get rid of your API schema with trPC. So I want to start my talk with schema fatigues. So we have two main way to communicate from your server and client. We have open API, and we have GraphQL. So open API is open API specification, the final language agnostic interface. So you know HTTP verbs like POST, GET, PATCH, DELETE, et cetera, et cetera. And it's a new language to know.

So if you want to use open API, you have to learn a new specification. Then you need to write case-sensitive JSON or YAML. By the way, YAML sucks. And you have to generate your schema, your type script types, every time you change something into the open API documentation.

Let's see the GraphQL part. With GraphQL, it's an open-source data query, manipulation language, again language, and you need to learn new things. So it's a GraphQL format. And you need to learn the new specification, so query, mutations, stuff like that, so on and so forth. And then you have always to generate your type script types. So if you change something in the GraphQL, you need to generate this type and you dump it into the client.

I'm struggling a lot with this kind of things because I'm working in a consultancy company, Flowing, and I found a solution in TRPC, and then I will show you how.

My handle in LinkedIn and Twitter is Giorgio underscore boa. If you want to tweet about this talk and tag me and tag also the conference, I really appreciate.

So let's jump back to TRPC. TRPC is a quite famous library. More than 100,000 weekly npm downloads and more than 60,000 stars on GitHub. So quite popular. Okay. All the library is based on this type of that you can see on the screen. Okay.

2. Implementing TRPC with Next JS and Prisma

Short description:

The library is based on extracting the shape of an object using TRPC. A Next JS application is used to demonstrate the implementation of TRPC and its integration with Prisma. The author router is defined with different procedures for getting a list of authors, adding authors, and deleting authors. The Prisma API is used in the business logic to interact with the database. In the client folder, the TRPC file is defined with the up router obtained from the server folder.

All the library is based on this type of that you can see on the screen. Okay. So here we have an object. My job object with my first name and last name. And with the type of, we are able to extract the shape of this object to get a type. Okay. And now we will show how it works with TRPC.

Here I have a next JS application, a simple one, and I decided to add from scratch TRPC to show you how easy it is to implement it. So I created also a connection with Prisma because TRPC and Prisma are really a big match. Okay. So here we have our schema, Prisma schema is our model, model author, okay, and we have a seed because Prisma can help us with the seed in our database if it is empty. Okay, we have a source folder, and as you may say, know, in pages we have the slash API folder. Inside of API folder we have we need to create a tRPC folder, and inside of a tRPC folder we need to define a file like this one with square brackets, and next for us grab all the query parameters and give us the information. So we need to expose this endpoint. In this endpoint we define from tRPC next with this API, we define our endpoint. In this endpoint we have a few configurations, but the most important thing is this up-router. In this up-router we have the possibility to define many routers. Here we have only the author router and here we have the typeof I mentioned before. So, from this object we are extracting the shape of the object and defining the up-router. This type is really important for the client. And now we will see how. This is my author router and in this author router, I have a few different procedures. So, I define to get a list of authors, I can add authors and then I can delete one, of course. So, this is my business logic and in the business logic, I put the Prisma API. So, Prisma author dot find many or, for example, if I want to add a new author, Prisma author find first and then if it's not present, I will create the record.

Okay, but let's jump to the client. We see before that we are export type up router. So, we are extracting the shape of this router and now in the client folder, we define the TRPC file, and in this file, there is a few configuration, but the most important part is this one create TRPC next with the generic and here we define up router. The up router arrive directly from the folder we saw before. So, server routers underscore app.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Step aside resolvers: a new approach to GraphQL execution
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
GraphQL has made a huge impact in the way we build client applications, websites, and mobile apps. Despite the dominance of resolvers, the GraphQL specification does not mandate their use. Introducing Graphast, a new project that compiles GraphQL operations into execution and output plans, providing advanced optimizations. In GraphFast, instead of resolvers, we have plan resolvers that deal with future data. Graphfast plan resolvers are short and efficient, supporting all features of modern GraphQL.
Handling Breaking Changes in GraphQL
GraphQL Galaxy 2022GraphQL Galaxy 2022
22 min
Handling Breaking Changes in GraphQL
Top Content
This Talk discusses handling breaking changes in a GraphQL schema, including the use of the deprecated directive to tag fields that should no longer be used. It also covers the process of deploying GraphQL APIs and mobile apps, highlighting the challenges of mobile app release adoption. The Talk emphasizes the importance of making safe upgrades in mobile apps and provides strategies for detecting and handling breaking changes, such as using TypeScript and GraphQL Inspector. Overall, the Talk emphasizes the need to minimize user impact when introducing breaking changes in GraphQL schemas.
Advanced Patterns for API Management in Large-Scale React Applications
React Advanced Conference 2021React Advanced Conference 2021
20 min
Advanced Patterns for API Management in Large-Scale React Applications
Top Content
This Talk covers advanced patterns for API management in large-scale React applications. It introduces the concept of an API layer to manage API requests in a more organized and maintainable way. The benefits of using an API layer include improved maintainability, scalability, flexibility, and code reusability. The Talk also explores how to handle API states and statuses in React, and provides examples of canceling requests with Axios and React Query. Additionally, it explains how to use the API layer with React Query for simplified API management.
Safely Handling Dynamic Data with TypeScript
Node Congress 2021Node Congress 2021
29 min
Safely Handling Dynamic Data with TypeScript
Top Content
This Talk discusses the safe handling of dynamic data with TypeScript using JSON Schema and TypeBox. Fastify, a web framework, allows developers to validate incoming data using JSON schema, providing type safety and error handling. TypeBox is a powerful library that allows developers to define JSON schemas and derive static types in TypeScript. The combination of JSON schema, TypeBox, and Fastify provides powerful tools for type safety and validation of dynamic data.
APIs are Evolving. Again.
JSNation 2023JSNation 2023
28 min
APIs are Evolving. Again.
Matteo Collina
Luca Maraschi
2 authors
Technology is a spiral, with foundational ideas resurfacing. Java revolutionized enterprise applications. REST and JSON simplified building APIs and websites. Node.js enabled fast and custom development, leading to the microservices revolution. Platformatic aims to fill the gap in building, managing, and scaling microservices painlessly.
Ref() vs. Reactive(): What to Choose Using Vue 3 Composition API?
Vue.js London 2023Vue.js London 2023
22 min
Ref() vs. Reactive(): What to Choose Using Vue 3 Composition API?
This talk compares Rev and Reactive in Vue 3, exploring reactivity and their limitations. It discusses the use of watchers, identity issues, and migration strategies. The talk also highlights the benefits of using the Ref function for better reactivity and the recommended pattern of grouping Refs. Opinions from the Vue community are shared, with a majority preferring Ref over Reactive.

Workshops on related topic

Hands-on with AG Grid's React Data Grid
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
WorkshopFree
Sean Landsman
Sean Landsman
Get started with AG Grid React Data Grid with a hands-on tutorial from the core team that will take you through the steps of creating your first grid, including how to configure the grid with simple properties and custom components. AG Grid community edition is completely free to use in commercial applications, so you'll learn a powerful tool that you can immediately add to your projects. You'll also discover how to load data into the grid and different ways to add custom rendering to the grid. By the end of the workshop, you will have created an AG Grid React Data Grid and customized with functional React components.- Getting started and installing AG Grid- Configuring sorting, filtering, pagination- Loading data into the grid- The grid API- Using hooks and functional components with AG Grid- Capabilities of the free community edition of AG Grid- Customizing the grid with React Components
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.
Database Workflows & API Development with Prisma
Node Congress 2022Node Congress 2022
98 min
Database Workflows & API Development with Prisma
WorkshopFree
Nikolas Burk
Nikolas Burk
Prisma is an open-source ORM for Node.js and TypeScript. In this workshop, you’ll learn the fundamental Prisma workflows to model data, perform database migrations and query the database to read and write data. You’ll also learn how Prisma fits into your application stack, building a REST API and a GraphQL API from scratch using SQLite as the database.
Table of contents:
- Setting up Prisma, data modeling & migrations- Exploring Prisma Client to query the database- Building REST API routes with Express- Building a GraphQL API with Apollo Server
Best Practices and Patterns for Managing API Requests and States
React Advanced Conference 2022React Advanced Conference 2022
206 min
Best Practices and Patterns for Managing API Requests and States
Workshop
Thomas Findlay
Thomas Findlay
With the rise of frameworks, such as React, Vue or Angular, the way websites are built changed over the years. Modern applications can be very dynamic and perform multiple API requests to populate a website with fresh content or submit new data to a server. However, this paradigm shift introduced new problems developers need to deal with. When an API request is pending, succeeds, or fails, a user should be presented with meaningful feedback. Other problems can comprise API data caching or syncing the client state with the server. All of these problems require solutions that need to be coded, but these can quickly get out of hand and result in a codebase that is hard to extend and maintain. In this workshop, we will cover how to handle API requests, API states and request cancellation by implementing an API Layer and combining it with React-Query.
Prerequisites: To make the most out of this workshop, you should be familiar with React and Hooks, such as useState, useEffect, etc. If you would like to code along, make sure you have Git, a code editor, Node, and npm installed on your machine.