0
0
Astroframework~3 mins

Why Fetching APIs in frontmatter in Astro? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how fetching data early can make your website feel instant and polished!

The Scenario

Imagine you want to show the latest news on your website. You write code to fetch data from an API inside your page's main content. Every time the page loads, it waits for the data, making the site slow and clunky.

The Problem

Fetching data manually inside page content causes delays and flickers. The page might show empty content first, then update, confusing visitors. It also repeats the same fetch on every visit, wasting time and resources.

The Solution

Fetching APIs in frontmatter lets you get data before the page builds. This means your page has all the info ready when it loads, making it fast and smooth without flickers or delays.

Before vs After
Before
const response = await fetch('https://api.example.com/data'); const data = await response.json(); return <div>{data.title}</div>;
After
---
const response = await fetch('https://api.example.com/data');
const data = await response.json();
---
<div>{data.title}</div>
What It Enables

This approach enables lightning-fast pages that load complete data instantly, improving user experience and reducing server load.

Real Life Example

A blog site fetching latest posts from an external API in frontmatter shows all posts immediately when the page loads, without waiting or flickering.

Key Takeaways

Manual API calls inside page content slow down loading and cause flickers.

Fetching APIs in frontmatter gets data before rendering, making pages fast and smooth.

This method improves user experience and optimizes resource use.