Data Fetching
Purpose and Scope
Data fetching in Astro is the pattern of loading external or internal data while rendering a page, component, endpoint, or server response. For authors, the important rule is timing: a fetch in an Astro component script runs while Astro renders that component. In a static build, that means the request happens during astro build and the resulting HTML is written with the fetched data already present. In a server-rendered project, the same authoring pattern can run at request time, so response data may vary per user, cookie, URL, or deployment environment.
Astro’s official data fetching guidance centers on the standard global fetch() function. Astro components can use top-level await in their frontmatter component script, fetch a full external URL, parse the response, and then render the result directly or pass it as props to Astro and framework components. When fetching from your own project, construct a URL relative to the current request with new URL('/api', Astro.url) so the request targets an on-demand page or endpoint in the same deployment rather than assuming a hard-coded host.
The source paths for this page show the repository systems that make those authoring patterns safe at build time and portable across packages. Build configuration standardizes how packages compile from src to dist, the Cloudflare changeset documents a rendering failure mode where page exceptions during prerendering must fail the build, and the font asset infrastructure shows how build-time URL generation preserves base paths, asset prefixes, content hashes, CSP resources, and adapter-level search parameters. Those details matter because fetched content often references assets, and build-time rendering must surface failures rather than emit incomplete pages.
Sources: .changeset/sharp-bags-build.md, configs/tsconfig.build.json, packages/astro-prism/tsconfig.build.json, packages/astro-rss/tsconfig.build.json, packages/astro/src/assets/fonts/infra/build-font-file-id-generator.ts, packages/astro/src/assets/fonts/infra/build-url-resolver.ts
Core Primitives
The first primitive is the Astro component script: the frontmatter block at the top of an .astro file. Use it to call fetch(), read JSON, and assign values that the template can render. The official example fetches a random user, reads data.results[0], prints the user name, and passes the email or city into child components. This is intentionally ordinary JavaScript, so the same mental model applies to REST APIs, JSON files, CMS endpoints, or internal API routes that return a Response.
The second primitive is render mode. In a static site, data fetching participates in the build pipeline: every page that uses fetched data must complete successfully before the final output is trustworthy. The changeset for Cloudflare’s workerd integration documents a concrete build concern: prerender errors thrown while pages render must not be silently swallowed, because that can produce truncated HTML and a successful exit code. The fix described there buffers the response body before returning it to the build process so streaming rendering errors become visible build failures.
The third primitive is URL construction. Internal fetches should be based on the current Astro URL, while generated asset URLs must honor the deployment base and asset prefix. BuildUrlResolver accepts a base, an AssetsPrefix, and search parameters, then resolves an id into a URL path. It records either the external asset prefix or 'self' as a CSP resource and appends any supplied search parameters before storing the final URL. This supports deployments where adapters add tracking parameters, including skew-protection-style metadata, without forcing application data fetching code to know the asset pipeline details.
Execution Flow
A typical static data-fetching page starts with an .astro component script that awaits an API request. Astro evaluates that script during the build, then renders the template using the resolved data. If the fetched data is passed into a framework component without a client directive, the component can still be rendered as part of the generated HTML. If the framework component uses a client:* directive, the same data may become initial props for client-side interactivity. This separation lets most of a page remain static while a specific island hydrates in the browser.
A typical server-rendered flow uses the same component code but changes when it runs. With server rendering enabled, the fetch occurs when the request is handled. That makes it appropriate for user-specific data, session-dependent responses, request headers, or endpoints that should not be baked into static HTML. The official astro/fetch reference also describes lower-level routing handlers built on the Fetch API, including a per-request FetchState that tracks the request, URL, pathname, route data, cookies, locals, params, and status. That API belongs to advanced routing composition rather than basic component authoring, but it shows how Astro’s server pipeline is still organized around Fetch-compatible request and response objects.
Prefetching is related but distinct. Data fetching loads data needed to render a page; prefetching asks the browser to request another internal page before navigation. Astro’s official prefetch guide describes enabling prefetch: true and adding data-astro-prefetch to internal links. Strategies such as hover, tap, viewport, and load tune when navigation requests are made. This improves perceived page speed for multi-page applications, but it does not replace server or build data fetching. External links are not prefetch targets, and bandwidth-sensitive conditions can alter the strategy.
System-to-Code Mapping
The build configuration files show how repository packages that participate in rendering and content output are compiled consistently. The shared build tsconfig extends the base config, sets rootDir to a package src directory, emits to dist, and stores TypeScript build info under dist/._cache/ts_build/build.tsbuildinfo. Package-specific configs such as packages/astro-rss/tsconfig.build.json and packages/astro-prism/tsconfig.build.json inherit that convention, with Prism additionally including virtual.d.ts. For data-fetching users, this is mostly invisible, but it is part of the release discipline that keeps helper packages usable in build-time rendering workflows.
The asset infrastructure shows how fetched or generated page output stays deployable when assets are emitted during the build. BuildFontFileIdGenerator receives a hasher and a content resolver, resolves the original font URL to content, hashes that content, and returns an id with the font type as the extension. BuildUrlResolver then turns an emitted id into the URL a rendered page can use. Together, these classes make build output depend on content identity and deployment configuration rather than on incidental source filenames. That same principle is important when fetched data references generated assets: the final HTML should point at stable, correctly prefixed URLs.
| Concern | Source-backed implementation signal | Reader impact |
|---|---|---|
| Build compilation | Shared package build config emits src to dist with cached TypeScript build info | Published packages used during rendering follow one build convention |
| Package inheritance | RSS and Prism package configs extend the shared build config | Rendering helpers and integrations are built consistently |
| Prerender failures | Cloudflare changeset buffers workerd responses so thrown page errors fail builds | Build-time data or rendering errors should be visible, not hidden in truncated HTML |
| Asset URL generation | Font URL resolver applies base, asset prefix, search params, and CSP tracking | Rendered pages keep valid asset URLs across deployment targets |
| Content-derived ids | Font file id generator hashes resolved content and appends type | Build output can be cacheable and content-addressed |
Compact Reference
Use fetch() in an Astro component script when the data is needed to generate markup. Use a full URL for external APIs, and use new URL('/api', Astro.url) for internal pages or endpoints that are rendered on demand. Prefer top-level await in the component script for clarity. Pass the resulting values as props to Astro components or framework islands when the data should feed a reusable view component. Remember that the same syntax has different timing depending on output mode: build time for prerendered pages, request time for server-rendered pages.
---
const response = await fetch('https://example.com/data.json');
const data = await response.json();
---
<h1>{data.title}</h1>For internal navigation performance, configure prefetching separately from data loading. A minimal project-level setting is prefetch: true, then links can opt in with data-astro-prefetch. Use data-astro-prefetch='tap', hover, viewport, or load when a specific link needs a different strategy. Treat this as a navigation enhancement, not a way to fetch arbitrary API data for a component.
import { defineConfig } from 'astro/config';
export default defineConfig({
prefetch: true,
});Relevant Source Files
.changeset/sharp-bags-build.md- Documents a build-rendering fix for Cloudflare workerd where prerender errors thrown by pages are buffered and surfaced as build failures instead of producing truncated HTML.configs/tsconfig.build.json- Defines the shared package build convention: packagesrcinput,distoutput, and TypeScript build-info caching underdist/._cache.packages/astro-prism/tsconfig.build.json- Shows a package-specific build config extending the shared build config while including both source files and a virtual declaration file.packages/astro-rss/tsconfig.build.json- Shows a package-specific build config that relies directly on the shared build settings for an output-oriented helper package.packages/astro/src/assets/fonts/infra/build-font-file-id-generator.ts- Implements content-based font file id generation by hashing resolved font content and appending the font type.packages/astro/src/assets/fonts/infra/build-url-resolver.ts- Implements build-time URL resolution for assets, including base paths, asset prefixes, search parameters, CSP resource tracking, and emitted URL tracking.
Next Steps
When adding data fetching to an Astro project, first decide whether the page should be prerendered or server-rendered. If the data is public, cacheable, and acceptable at build time, keep the fetch in the component script and let the generated HTML include the result. If the response depends on the incoming request, use server rendering or an endpoint and construct internal URLs from Astro.url. When output references generated assets, rely on Astro’s asset and font pipeline instead of hand-building paths, because deployment base paths and adapter parameters can affect the final URL.
Related pages to read next: endpoints for API route patterns, server-side-rendering-adapters for request-time rendering, content-collections for structured local content, and backend-services for combining actions, endpoints, and external services.