I am trying to call the internal API in app/api folder using fetch in server component. I am getting error during prerendering on deployment on vercel and netlify. I think it is because of the server is not yet available during building. How can I call the internal API using fetch in next js server components for populating data?
#Internal API call using fetch in server componets
16 messages · Page 1 of 1 (latest)
I also tried to accomplish the same but for some reason it does not work. Btw you can also skip your internal api and call external api directly from server component just fyi
Thank you for the response. But I am trying to fetch data from Contentful Headless CMS. I also have client componets that fetch this data. So, If I avoid using internal api for that, I have to use NEXT_PUBLIC for ENV variables for Space ID and Access Token which is not a good practice. The only way that I could find is to use internal api as proxy for both client and server componets. Or, are you suggesting usage of internal api for client components and direct external api fetching for server conponets?
Yes I suggest that. It might feel redundant but I know It is not recommended to call internal api from server components. I also hit same external api from both server component and client component but client component one goes through the route handler for security reasons
Yeah server component javascript is never exposed to the client so you are safe to directly call the external api from the server component.
Thank you. That approach worked 🙂
🎉
if u do need the internal api tho
i think right now the quick fix
is to put localhost in ur env file
i.e. add a thing to ur env variables
NEXT_PUBLIC_API=localhost:3000/api
then fetch
fetch(`${process.env.NEXT_PUBLIC_API}/my-route`)
now wherever you're hosting
you can add