Using route-handlers with local site
Answered
Transvaal lion posted this in #help-forum
Transvaal lionOP
I setup a route handler https://nextjs.org/docs/app/building-your-application/routing/route-handlers based on this similar to what we had in pages/api but I cant call await fetch(
/api/books) because it wants the full url? if I use env variable, it will fail on vercel deployment because the url is different.15 Replies
Transvaal lionOP
using page/api I could just do
await fetch('/api/books'Giant panda
Answer
Giant panda
TLDR: Don't fetch your own route handlers in server-side code.
Transvaal lionOP
@Giant panda thank you, ohhh, I didnt know about this, I created a custom api endpoint and I need to call that in pages, what does "instead just call the server-side logic directly" mean? is there a better example of what I need to do to make my endpoint work?
Giant panda
You copy the code from the route handler into your page
That's the whole point of server components
Transvaal lionOP
wouldnt this be a lot of repeated code?
Giant panda
No need for endpoitns
And if you need the same logic in multiple places you extract it into a reusable function and call that directly
Transvaal lionOP
I see, are there any other examples I can take a look?
Giant panda
The entire data fetching chapter does this all the time
Transvaal lionOP
okay, I get it now, thank you, I got confused between this route handler and the old pages/api but I think I understand it now
thank you
Giant panda
Simply put: route handlers are only for client-side fetching and 3rd parties accessing your public APIs.
Transvaal lionOP
thank you, I learned something new today! I got it fixed as you suggested, thank you