The type-safe guide to tRPC
This isn't the best guide to use tRPC, probably there are better ways to do this, like create-t3-app, the best I could find.
Most of what is here is from the tRPC's documentation, you can refer them, super helpful and easy to read.
What is tRPC?
tRPC is a typescript library, so to say, that makes it easy to create type-safe APIs without schema or any sort of code generation.
Where to use?
Create the typed server and then import its type and use it with an adaptor in the client side.
How does it implement type-safety?
tRPC encourages using the zod, a library for type validation of input and output arguments.
Is tRPC only limited to React?
tRPC's core API is built to work with any client, but right now it supports React and can be used with React Meta Frameworks like NextJS or SolidJS, since it uses React Query under the hood to talk to the server and maintaining type-safety across the data-pipeline or data-flow.
For now, it has first-party adaptors for React, NextJS, Express, Fastify, SolidJS, and some community packages like for tRPC for SveleteKit
What are its features?
- Lightweight, a tiny bundle size for such a powerful library.
- Type-safe to the max!
- Support subscriptions with websockets library.
- Request batching
- Request can be made simultaneously and then are batched into one.
- Strong User base and helpful Community
tRPC x NextJS
Recommended file structure:
unknown nodeComponents
Router
This is the router where the actual business logic will reside, create a backend folder inside the src directory and put all this stuff there.
If using prisma otherwise this is optional,src/server/utils/prisma.ts
src/server/router/context.ts
Using ContextsWe can create router without using the above context by just using trpc.router() that will work just fine. But if you are using some external API like in the above case we are using prisma, it's better to use pass in repeatedly used instances to context to avoid having multiple ones for every query we use that in, that may affect our performance and can also be vulnerable. src/server/router/index.ts
API handler aka NextJS adaptor:
The exact filename is necessary to make this work!
src/pages/api/trpc/[trpc].ts
Hooks
These are the React hooks necessary to maintain the type-safety, this will give you React Query like hooks to fetch the API.
src/utils/trpc.ts
Example query in React Component
Now that tRPC is set up, this is how we use it inside react components.
src/pages/index.tsx
SSG Helpers
SSG Helpers are helper functions that can be used to pre-fetch queries on the server upon request to reduce loading time.
They are to be used when working with SSR and SSG or ISR.
How to use it with getServideSideProps function of NextJS pages.
References