Fetch API data from server side from client
Answered
Iridescent shark posted this in #help-forum
Iridescent sharkOP
I want to fetch data from APIs on the back-end/server side as to not expose keys and such. Then, the client side can request that data from the server side and use it how it wants... With the pages route this would've been a /api/ page route but with the new app router this doesn't seem to be possible anymore. How can I do this?
I checked https://nextjs.org/docs/app/building-your-application/data-fetching/fetching but the example it gives uses a component, which I don't think I want. I just want to be able to request the data from the server side and let the client side do the rest of the work.
I checked https://nextjs.org/docs/app/building-your-application/data-fetching/fetching but the example it gives uses a component, which I don't think I want. I just want to be able to request the data from the server side and let the client side do the rest of the work.
Answered by B33fb0n3
I just want to be able to request the data from the server sideyou can do that by creating the promise serverside like this:
const dataPromise = fetch('https://api.vercel.app/blog') // no "await" so it stays a promise
And then use the
use
hook that awaits the promise inside your client component:const data = use(dataPromise);
I prefer awaiting the response inside my server component and only share the data that the client is allowed to see and the client really needs
@Iridescent shark
6 Replies
I just want to be able to request the data from the server sideyou can do that by creating the promise serverside like this:
const dataPromise = fetch('https://api.vercel.app/blog') // no "await" so it stays a promise
And then use the
use
hook that awaits the promise inside your client component:const data = use(dataPromise);
I prefer awaiting the response inside my server component and only share the data that the client is allowed to see and the client really needs
@Iridescent shark
Answer
Iridescent sharkOP
Thanks! Do I need to place
dataPromise
in a specific file or directory?@Iridescent shark Thanks! Do I need to place `dataPromise` in a specific file or directory?
no, you only need to pass it to the client component via props
Iridescent sharkOP
I'll try it out
Iridescent sharkOP
okay, I got something working :) thanks for the help!
sure thing