Using tRPC with a request to an external API
I have an API route that hits a third-party API. What role can tRPC play in this request? Can I create a new query in and move this
fetch
to the resolve
or am I not thinking about this correctly?GitHub
snapstock/[value].ts at main · jonyonson/snapstock
Contribute to jonyonson/snapstock development by creating an account on GitHub.
6 Replies
GitHub
snapstock/example.ts at main · jonyonson/snapstock
Contribute to jonyonson/snapstock development by creating an account on GitHub.
Here's where the TRPC example routes are
you can create a file in the same folder for your own routes
dont forget to add another .merge() call in the index.ts file
Thanks, that kind of make sense...but it's not weird to make an API call from that trpc route? I haven't seen an example of that and I'm still trying to wrap my head around all of this. Is there a benefit to making this external request through tRPC or would it be the same to just use a conventional next route?
its totally normal to make an api call from a trpc route
it would basically be the same to do it from a next route
except then you don't have trpc anymore
but both run in /api/whatever, ie on the server
The tRPC route doesn't do anything but run a function, and expect that function to return something it can send to the client. What you do in there is up to you. It can get data from a database, call an external API, send an email, send a text, start a robot... Whatever you want.
tRPC routes are pretty much 100% replacement for traditional routes outside of a few special cases. The benefit is that it's typesafe and easier to develop and use. Because it uses react query, it also integrates some light state management on the client side. But at the end of the day it's a nice way to write an API.