/

Optimizing Network Data Fetching in Astro

Optimizing Network Data Fetching in Astro

One of the inherent advantages of Astro is its flexible frontmatter feature.

Using frontmatter, we can execute JavaScript code, making it exceptionally convenient for fetching data during the build process.

Astro leverages the Fetch API which allows us to make network requests with ease.

Astro’s frontmatter supports top-level await, eliminating the need for complex solutions such as immediately-invoked function expressions (IIFE) or invoking async functions separately to utilize fetch(), which operates on promises.

To demonstrate this, we can directly use the await keyword within the frontmatter itself:

1
2
3
4
5
6
7
8
9
---
const res = await fetch('https://api.sampleapis.com/coffee/hot');
const data = await res.json();
---
<ul>
{data.map(item => (
<li>{item.title}</li>
))}
</ul>

It’s essential to emphasize that this network request occurs during the build process and only executes once when the site is deployed.

Naturally, subsequent deployments will trigger the network request again. Therefore, any changes made in the API will require triggering a rebuild. Most platforms offer options like webhooks to facilitate this process.

tags: [“Astro”, “frontmatter”, “Fetch API”, “network request”]