tRPC is a great tool for managing server-side procedures. However, it can be a bit tedious to import it in every `+page.server` file. In this article, I will show you how to optimize your code imports and avoid unexpected errors.
Updated
Chris Jayden
On This Page
I have been using tRPC for quite a while now and I'm absoluting loing it. While using though, I realized that I kept repeating imports in my SvelteKit +page.server files.
LIke any good developer, I decided to fix this problem. I created a utility function that would allow me to import tRPC only once and then use it in all my +page.server files.
Another crucial thing this utility tackles is rethrowing the right SvelteKit error object. The original error object thrown by tRPC is not the right one for SvelteKit and results in an unexpected error.
The utility function
All you need to do is import your appRouter and createTRPCContext functions and pass them to the utility function. Keep in mind that these might be named differently in your project.
The utility function will return a caller object that you can use to call your tRPC methods.
To illustrate how this utility can be used, here is a sample usage in +page.server. This eliminates repeating imports while allowing the ability to load in parallel.
Before
After
Epic right? This looks so much cleaner and is much easier to maintain.
In conclusion, tRPC combined with SvelteKit offers a powerful solution to manage server-side procedures.
Hopefully this utility will help you optimize your code imports and avoid unexpected errors.