Next.js Discord

Discord Forum

Is it possible to fetch from the API route in server?

Answered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
I am trying to fetch data from the api route in the server. but the fetch api and axios does not find the route and gives a 404 error. I may not know how to do that, so can you give me an example how to do that. keep in mind that I can do that on the client using useEffect() Hook but I wanted that to be done int the server.
Answered by joulev
Fetch and axios need the full path
View full answer

15 Replies

Answer
With domain and everything
The reason is that on the server all fetches are like fetches from nodejs, they dont have a “default” domain if it makes sense
Also, most likely you shouldn’t do that, instead just call server side functions directly https://nextjs-discord-common-questions.joulev.dev/fetching-own-api-endpoint-in-react-server-components
Asiatic LionOP
if I want to ship the code to the production, then I need to change all the URL to work correctly. is that correct? btw the code link you gave has work.
@Asiatic Lion if I want to ship the code to the production, then I need to change all the URL to work correctly. is that correct? btw the code link you gave has work.
I need to change all the URL to work correctly. is that correct?
yes; you need to edit localhost to your server domain
btw the code link you gave has work.
wdym?
Asiatic LionOP
i tried fetch(http://localhost:3000/api/hello) rn and it work.
@Asiatic Lion i tried fetch(http://localhost:3000/api/hello) rn and it work.
ofc firstly you need to have an endpoint running at localhost:3000/api/hello. secondly obv you need the " as well, fetch("https://localhost:3000/api/hello"), i was on phone so didn't add that
Asiatic LionOP
got it. I know how to work with fetch api but wasn't sure how to do that with api route in next.js
what do you mean?
@Asiatic Lion i tried fetch(http://localhost:3000/api/hello) rn and it work.
and it work.
oh sorry for some reasons my dumbass read it as "it didn't work"
i assume the issue is resolved right?
Asiatic LionOP
yes
thanks a lot