📄️ Define Routers
To begin building your tRPC-based API, you'll first need to define your router. Once you've mastered the fundamentals, you can customize your routers for more advanced use cases.
📄️ Define Procedures
Procedures in tRPC is a very flexible primitive to create backend functions; they use a builder pattern which means you can create reusable base procedures for different parts of your backend application.
📄️ Merging Routers
Writing all API-code in your code in the same file is not a great idea. It's easy to merge routers with other routers.
Your context holds data that all of your tRPC procedures will have access to, and is a great place to put things like database connections or authentication information.
📄️ API Handler
tRPC is not a backend of its own, but rather lives inside of other backends such as Next.js or Express. Despite that, most of tRPC's features and syntax are the same no matter which backend you are using. The API handler, also called adapter, enables this by acting as the glue between HTTP requests to your backend and tRPC.
You are able to add middleware(s) to a procedure with the t.procedure.use() method. The middleware(s) will wrap the invocation of the procedure and must pass through its return value.
📄️ Server Side Calls
You may need to call your procedure(s) directly from the server, createCaller() function returns you an instance of RouterCaller able to execute queries and mutations.
The createContext function is called for each incoming request, so here you can add contextual information about the calling user from the request object.
📄️ Output Validation
tRPC gives you automatic type-safety of outputs without the need of adding a validator; however, it can be useful at times to strictly define the output type in order to prevent sensitive data from being leaked.
📄️ Inferring Types
It is often useful to wrap functionality of your @trpc/client or @trpc/react-query api within other functions. For this purpose, it's necessary to be able to infer input types and output types generated by your @trpc/server router.
📄️ Error Handling
Whenever an error occurs in a procedure, tRPC responds to the client with an object that includes an "error" property. This property contains all the information that you need to handle the error in the client.
📄️ Error Formatting
The error formatting in your router will be inferred all the way to your client (& React components)
📄️ Data Transformers
You are able to serialize the response data & input args. The transformers need to be added both to the server and the client.
Procedure metadata allows you to add an optional procedure specific meta property which will be available in all middleware function parameters.
📄️ Response Caching
The below examples uses Vercel's edge caching to serve data to your users as fast as possible.