0
0
Astroframework~5 mins

Static vs server-side data fetching in Astro

Choose your learning style9 modes available
Introduction

Data fetching is how your website gets information to show. Static fetching gets data once when building the site. Server-side fetching gets data every time someone visits.

When your data rarely changes and you want fast page loads, use static fetching.
When your data changes often and must be fresh, use server-side fetching.
For blogs or portfolios with fixed content, static fetching works well.
For user dashboards or live updates, server-side fetching is better.
When you want to reduce server work, static fetching helps by doing work ahead.
Syntax
Astro
export async function getStaticPaths() {
  // returns paths for static/dynamic pages at build time
}

// Static fetching: fetch data directly in .astro frontmatter
// const res = await fetch('https://api.example.com/data');
// const data = await res.json();

// Server-side fetching:
// export const prerender = false;
// const res = await fetch('https://api.example.com/data');
// const data = await res.json();

Static fetching happens once during build, so pages load very fast.

Server-side fetching happens on every request, so data is always fresh but slower.

Examples
This fetches posts once when building the site. The posts stay the same until next build.
Astro
---
const res = await fetch('https://api.example.com/posts')
const posts = await res.json()
---
This fetches posts every time someone visits the page, so posts are always up to date.
Astro
---
export const prerender = false;
const res = await fetch('https://api.example.com/posts')
const posts = await res.json()
---
Sample Program

This Astro page fetches a todo item once during build time using static rendering (default). The page shows the todo details. The data won't change until you rebuild the site.

Astro
---
const res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
const todo = await res.json()
---
<html lang="en">
  <head>
    <title>Static Data Fetching Example</title>
  </head>
  <body>
    <h1>Todo Item</h1>
    <p>ID: {todo.id}</p>
    <p>Title: {todo.title}</p>
    <p>Completed: {todo.completed ? 'Yes' : 'No'}</p>
  </body>
</html>
OutputSuccess
Important Notes

Static fetching is great for speed but not for frequently changing data.

Server-side fetching can slow down your site if used too much.

Choose the method based on how fresh your data needs to be.

Summary

Static fetching gets data once at build time for fast pages.

Server-side fetching gets data on every request for fresh content.

Pick static for stable data, server-side for dynamic data.