- Published on
Next.js with tRpc
Next.js with tRpc
Over this last winter I had the pleasure of getting very familiar with the t3 stack. If you haven’t heard of it yet, it’s a combination of Next.js and tRpc (and other fun stuff like Tailwind). I’ve worked on a couple different Next.js projects in the past and really love the development experience but, like with many frontend projects, things can get wobbly when trying to unify your endpoint response types with your frontend types system.
Having used Typescript for the last five or so years, I’ve grown to love the dev experience and the sense of speed it gives when writing code. There is, of course, a learning curve in the beginning but once you’ve gotten a handle on Typescript, there’s really no going back. I’ve spent the last few months learning Scala, but that’s a different blog post 😅.
Typescript is where tRpc really shines when coupled with Next.js. If you plan to build a full stack application with the Node ecosystem, you’ll be blown away at how simple and really friendly this stack is.
Often when writing data fetchers in Next.js, you’ll try to put this logic in the
getServerSideProps functions, which will both happen server side. Then you’ll either build an api route to consume this request and manage all the server level logic (think controller and repo, but not really). The problem is that we can’t share the types of the response in a very intuitive or ergonomically pleasing way. This is where tRpc is awesome.
tRpc basically becomes middleware for you api routes. Or an abstraction, if you will. Once it’s hooked up, you simply create a “router” with methods for your server logic. Then on the client side (if using Next.js specifically) you can access the methods you defined server side in the React component itself! With type inference! It’s kind of magic once you get the hang of it.
I’ll need to setup a demo project since the one I contributed to over the winter got lost in history (and no longer belongs to me). I jammed this blog out in an evening because I’ve been thinking lately about how much I liked the t3 stack and trpc. Updates soon!