Next.js Discord

Discord Forum

Call API EndPoint in getServerSideProps using Fetch or what?

Unanswered
Armenian Gampr dog posted this in #help-forum
Open in Discord
Avatar
Armenian Gampr dogOP
I know it's not a recommended way but when I try to implement this, it doesn't work and the endpoint throws 401 error.

The alternative way I tried was -> created a function of logic and used it in getServerSideProps.
Since, I am using firebase, it throws error.
Make sure you call initializeApp() before using any of the Firebase services.

Now, where ever I try to initializeApp(), it still throws the same error.

The API route works fine from CURL or Browser but not in the getServerSideProps.

I really apologise if this sound like a noob question but I want to understand this whole flow thing.
In general, "Not recommended way" is a way that works but is not recommended while here not recommended way is something which isn't supposed to work or I am missing something!

19 Replies

Avatar
Toyger
where is your api endpoint? is it some custom API or what?
Avatar
Armenian Gampr dogOP
it's the api inside of nextjs.
i.e. /pages/api/getData.js
Avatar
Ray
are you trying to call /api/getData in getServerSideProps?
Avatar
Armenian Gampr dogOP
yup, it throws 401 in case of calling the API
Avatar
Ray
oh you shouldn't do that
you should do whatever you do in api route in getServerSideProps
instead of fetching it
Avatar
Armenian Gampr dogOP
actually, I did that in my 2nd approach, I made a fn out of the logic and called it inside the getServerSideProps, but it came with different issues but related to next firebase auth 😦
but why is it like it throws 401, shouldn’t we be able to consume the API from wherever we want?
Avatar
Ray
how do you fetch it?
401 properly return from firebase?
btw, if you are fetching firebase in getServerSideProps which mean you are fetching it on server side.
you should use firebase-admin instead
firebase is for web browser
might not work with node
Avatar
Armenian Gampr dogOP
I meant, for the pages/api end point, shouldn’t we be able to use it from anywhere we want?
Avatar
Ray
yes but not inside getServerSideProps
Avatar
Armenian Gampr dogOP
gotcha, thank you for clearing it out, I will copy the logic to the getServerSideProps and use like suggested.