Salta ai contenuti

Data Fetching

Questi contenuti non sono ancora disponibili nella tua lingua.

.astro files can fetch remote data to help you generate your pages.

All Astro components have access to the global fetch() function in their component script to make HTTP requests to APIs using the full URL (e.g. Additionally, you can construct a URL to your project’s pages and endpoints that are rendered on demand on the server using new URL("/api", Astro.url).

This fetch call will be executed at build time, and the data will be available to the component template for generating dynamic HTML. If SSR mode is enabled, any fetch calls will be executed at runtime.

💡 Take advantage of top-level await inside of your Astro component script.

💡 Pass fetched data to both Astro and framework components, as props.

import Contact from '../components/Contact.jsx';
import Location from '../components/Location.astro';
const response = await fetch('');
const data = await response.json();
const randomUser = data.results[0];
<!-- Data fetched at build can be rendered in HTML -->
<h2>{} {}</h2>
<!-- Data fetched at build can be passed to components as props -->
<Contact client:load email={} />
<Location city={} />

fetch() in Framework Components

Section titled fetch() in Framework Components

The fetch() function is also globally available to any framework components:

import type { FunctionalComponent } from 'preact';
const data = await fetch('').then((response) =>
// Components that are build-time rendered also log to the CLI.
// When rendered with a client:* directive, they also log to the browser console.
const Movies: FunctionalComponent = () => {
// Output the result to the page
return <div>{JSON.stringify(data)}</div>;
export default Movies;

Astro can also use fetch() to query a GraphQL server with any valid GraphQL query.

const response = await fetch("",
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
query: `
query getFilm ($id:ID!) {
film(id: $id) {
variables: {
id: "ZmlsbXM6MQ==",
const json = await response.json();
const { film } =;
<h1>Fetching information about Star Wars: A New Hope</h1>
<h2>Title: {film.title}</h2>
<p>Year: {film.releaseDate}</p>

Astro components can fetch data from your favorite CMS and then render it as your page content. Using dynamic routes, components can even generate pages based on your CMS content.

See our CMS Guides for full details on integrating Astro with headless CMSes including Storyblok, Contentful, and WordPress.


A cosa stai pensando?

Crea una Issue su GitHub

Il modo più rapido per segnalare un problema al nostro team.