Introduction
Fetching APIs in frontmatter lets you get data before your page shows. This means your page can use fresh info right away.
Fetching APIs in frontmatter lets you get data before your page shows. This means your page can use fresh info right away.
--- const response = await fetch('https://api.example.com/data'); const data = await response.json(); ---
await here because Astro supports async frontmatter.users.--- const res = await fetch('https://api.example.com/users'); const users = await res.json(); ---
--- const res = await fetch('https://api.example.com/weather'); const weather = await res.json(); ---
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.
--- 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>
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.
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.
data.message in the component?
---
const response = await fetch('https://api.example.com/greet');
const data = await response.json();
---
{data.message}
Assuming the API returns JSON: { "message": "Hello, Astro!" }---
const data = fetch('https://api.example.com/data');
const json = data.json();
------
// Option A
const res = await fetch('https://api.example.com/users');
const users = await res.json();
---
Pass the test and this pattern moves unknown