#Using fetch on server

1 messages · Page 1 of 1 (latest)

thorn frigate
#

Im calling an API in an astro component with a helper funcion and i use this data as props to another components, i think i have to use prerender = false, becuase it tries to use the data to create static pages

uneven steepleBOT
#

Hi @thorn frigate. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You only need to set export const prerender = false if you want your page or endpoint to be rendered on demand (i.e., at request time on the server), rather than being statically generated at build time. By default, Astro prerenders pages and fetches data at build time, so if your API call returns different data on each request or relies on request-specific information (like cookies or headers), you should opt out of prerendering by setting prerender = false in your Astro component. This will ensure the data is fetched on the server for each request, not just once at build time.

Example:

---
// src/pages/my-page.astro
export const prerender = false;
import MyComponent from '../components/MyComponent.astro';
const data = await fetch('<https://api.example.com/data'>).then(res => res.json());
---
<MyComponent someData={data} />

If your data is static or doesn't change per request, you can leave prerendering enabled (the default), and Astro will fetch the data at build time and generate static HTML.

In summary:

  • Use prerender = false if you need fresh data on every request or your data is request-specific.
  • Otherwise, you can let Astro prerender the page and fetch the data at build time for better performance see docs see data fetching.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@thorn frigate Kapa.ai is still learning and improving, please let me know how I did by reacting below.

thorn frigate
#

Do i have to use prerender = false

#

Do i have to use prerender = false when i use Astro server actions?@uneven steeple

uneven steepleBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Yes, you must use export const prerender = false on any page where you want to call Astro server actions from an HTML form action. This is because actions require the page to be rendered on demand, not statically at build time. The documentation states:

Pages must be on-demand rendered when calling actions using a form action. Ensure prerendering is disabled on the page before using this API.

So, if you are using server actions in a way that requires server-side execution (such as handling form submissions), you need to disable prerendering for that page by setting export const prerender = false at the top of your Astro component Call actions from an HTML form action.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: