0
0
Astroframework~5 mins

Fetching APIs in frontmatter in Astro

Choose your learning style9 modes available
Introduction

Fetching APIs in frontmatter lets you get data before your page shows. This means your page can use fresh info right away.

You want to show weather info on your page that updates every time.
You need to get a list of blog posts from an online source before showing them.
You want to display user profiles fetched from a server when the page loads.
You want to get product details from an API to show in a shop page.
Syntax
Astro
---
const response = await fetch('https://api.example.com/data');
const data = await response.json();
---
The frontmatter is the top part of an Astro file between triple dashes (---).
You can use await here because Astro supports async frontmatter.
Examples
Fetches a list of users from an API and stores it in users.
Astro
---
const res = await fetch('https://api.example.com/users');
const users = await res.json();
---
Fetches current weather data to use in the page.
Astro
---
const res = await fetch('https://api.example.com/weather');
const weather = await res.json();
---
Sample Program

This Astro component fetches a post from a public API before the page loads. Then it shows the post's title and body inside the page.

Astro
---
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const post = await res.json();
---

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Post Example</title>
  </head>
  <body>
    <h1>{post.title}</h1>
    <p>{post.body}</p>
  </body>
</html>
OutputSuccess
Important Notes

Always check if the API URL is correct and accessible.

Use await to wait for the data before using it in your page.

Fetching in frontmatter means data is ready when the page renders, improving user experience.

Summary

Fetching APIs in frontmatter gets data before the page shows.

Use await fetch() inside the triple dash section at the top.

This helps show fresh data right away on your page.