How Astro is built
By Flavio
Tagged: Astro
I wanted to know what Astro does when we run astro build. Let's follow one page from its .astro file to the final HTML in dist.
I use Astro every day, and for a long time I never stopped to think about what it’s doing under the hood. I write a page, run astro build, and a dist folder pops out.
Then I got curious. What really happens between a .astro file and the HTML that ends up on disk? I opened the Astro source code and traced a small page with a single interactive React component all the way through the build.
If you’re new to Astro, start with my free Astro course. Here I’ll skip the basics and walk through the build pipeline itself.
Astro does more than compile .astro files
Going in, I assumed Astro compiled .astro files and handed everything else off to Vite. It does that, sure, but it also discovers routes, loads content, renders pages, writes static files, and wires up server builds.
The Rust compiler only ever looks at one .astro file at a time. Vite is what stitches that compiled file together with its components, styles, scripts, and assets. Along the way, Astro tracks which components need JavaScript in the browser: any framework component compiles down to plain HTML unless you opt it in with a client:* directive.
A quick overview
Here’s how the main stages line up during a build:
Instead of spitting out a finished site, the Rust compiler turns one .astro file into a server module plus metadata, and Vite connects that module to the rest of your project. Astro then runs that server bundle to generate the HTML.
One thing that surprised me: a static build runs the exact same renderer as a server-rendered page. It just executes the render during the build and saves the response to disk.
Where the code lives
The main Astro repository is a pnpm monorepo split into these package groups:
packages/
astro/ CLI, config, routing, build, and runtime
create-astro/ project creation command
integrations/ React, Vue, Svelte, adapters, and other integrations
markdown/ unified and Satteri Markdown processors
language-tools/ editor, language server, and astro check
internal-helpers/ shared private utilities
telemetry/ anonymous telemetry client
The core lives in packages/astro, which holds the CLI, build pipeline, router, and production runtime. Framework renderers sit outside core, so React, Preact, Vue, Svelte, and Solid each ship as separate integrations. Deployment adapters work the same way: Node, Cloudflare, Netlify, Vercel, and Deno all package the same core app differently.
For Markdown, Astro 7 defaults to the Rust-based Satteri processor, hooked into Astro’s Markdown interface through @astrojs/markdown-satteri.
Two big pieces live outside the monorepo entirely. The .astro compiler is in withastro/compiler-rs, which bundles the Rust parser integration, code generator, Node-API binding, and JavaScript wrapper. And Vite is its own dependency: Astro 7 runs on Vite 8, which uses Rolldown for production builds. Astro layers its own plugins on top and tells Vite what to bundle. If you want a quick primer on Vite first, check out my Vite tutorial.
The page we’ll use
To keep things concrete, let’s trace a tiny Astro page with one React island. (If .astro syntax is new to you, my guide to Astro components covers the basics.) Here’s src/pages/index.astro:
---
import Counter from '../components/Counter.jsx'
const title = 'How Astro works'
---
<html lang="en">
<head>
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
<Counter start={1} client:visible />
</body>
</html>
<style>
h1 {
color: rebeccapurple;
}
</style>
And here’s the React component it imports:
import { useState } from 'react'
export default function Counter({ start }) {
const [count, setCount] = useState(start)
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
)
}
This setup assumes the React integration is already installed. If you need the steps, I wrote a short guide on how to add a React component to an Astro project.
Without client:visible, Astro renders Counter to static HTML and ships zero JavaScript for it. With client:visible, Astro still renders that initial HTML on the server, while also creating a browser entry point so the component can hydrate later.
Let’s follow this page from the terminal command all the way into the bundle.
astro build starts in the CLI
Running astro enters at packages/astro/bin/astro.mjs. Before doing anything else, this small entry script checks that your Node.js version is supported and normalizes lowercase Windows drive letters, which Vite can’t process properly. Then it imports the compiled CLI module and passes process.argv along.
The CLI dispatcher parses your flags with yargs-parser and routes to dev, build, preview, sync, or whichever command you ran. For astro build, it lazy-imports only the build command so unrelated commands don’t slow down startup. From there, it turns CLI flags into inline Astro config and calls the core build function, keeping the CLI layer thin so it only handles options and terminal output.
Astro loads the configuration
The core build begins in core/build/index.ts. First, it switches the process environment to production, unless you passed --devOutput to keep development mode on for debugging.
Next, resolveConfig() locates the project root and looks for a config file in this order:
astro.config.mjs
astro.config.js
astro.config.ts
astro.config.mts
For a JavaScript config file, Astro tries a native import() first. If that fails, or if you’re using a TypeScript config, it spins up a temporary Vite server so it gets normal Vite module resolution.
Once loaded, Astro merges the config file with any CLI flags (inline flags win) and validates the result with Zod. If anything fails schema validation, the build stops right there before scanning routes or compiling a single file.
After validation, Astro builds its internal settings object and runs integration hooks. Integrations can modify settings during astro:config:setup, which is the same hook you’d use if you write your own package (I walk through the full process in how to build an Astro integration).
This is also where Astro decides the main output mode. The default output: 'static' prerenders pages unless a route opts out, while output: 'server' switches the default to on-demand rendering. Any individual route can flip the default with export const prerender. If even one route needs server rendering and you haven’t installed an adapter, Astro throws NoAdapterInstalled during setup.
Astro finds the pages
With config ready, Astro scans src/pages using createRoutesList(). It walks the directory tree looking for .astro, Markdown, MDX, and any other configured page extensions, while turning JavaScript and TypeScript files into endpoints. Files starting with _ and hidden files get skipped, except for .well-known.
Each matching file gets converted into route segments, parameters, a regular expression, and output metadata. Our src/pages/index.astro maps cleanly to /, while something like src/pages/products/[id].astro records an id parameter and a dynamic pattern. Astro mixes in any injected routes and configured redirects, then sorts everything by matching priority.
Before bundling starts, the scanner also inspects each route’s source to read its prerender option and catches route collisions early. Dynamic static routes still need getStaticPaths(), though Astro waits to evaluate that function until it has built the server module.
Content collections load before rendering
Our small example doesn’t use content collections, but plenty of Astro sites do, and Astro loads them before any pages get rendered.
During build setup, syncInternal() starts a temporary Vite server to load src/content.config.ts along with whatever modules your loaders import, and writes generated collection types into .astro.
Then ContentLayer kicks off every collection loader in parallel. Each loader gets a store scoped to its own collection, so it can replace all entries, update a subset, or save metadata for later syncs. Astro validates every entry against the collection schema and writes the resulting data store to its cache.
Pages query that fixed snapshot through getCollection() or getEntry(). Both prerendered and on-demand pages can use it, though build-time collections stay frozen once deployed. If you need request-time data, Astro’s live collections run on a separate runtime path.
Astro configures Vite
Now Astro builds its Vite config in create-vite.ts, and reading this file shows just how much wiring Astro handles for you. Its built-in plugin list covers routes, renderers, .astro files, scripts, styles, Markdown, content, middleware, assets, actions, sessions, and islands.
Astro starts with its required base config and merges four layers in order, with later layers overriding earlier ones:
- Astro’s common Vite configuration.
- Your own
viteconfiguration. - Vite changes added by Astro integrations.
- Configuration specific to the current command.
Astro also sets Vite’s application type to custom, telling Vite to skip its default HTML app fallback because Astro owns request handling. At this point, Vite has everything it needs to build the project’s module graphs.
The Rust compiler turns .astro into JavaScript
As Vite walks the module graph, it asks plugins to transform every file it encounters. Any file ending in .astro goes to the astro:build Vite plugin, which runs ahead of normal transforms. In the client environment, it swaps out .astro server code for a tiny safe stub.
On the server side, the plugin calls compileAstro(), which delegates to the core compiler wrapper. That wrapper runs style preprocessors like Sass first, then hands the file to transform() in @astrojs/compiler-rs. On supported platforms, the JS wrapper loads a native binary; if none is available, it falls back to WebAssembly (WASI).
Inside Rust, the Node-API binding sets up an Oxc allocator and parses the file with Oxc’s Astro source type into an Astro AST (abstract syntax tree). If parsing fails, it returns labeled diagnostics and stops right there instead of continuing with a broken tree.
Next, the Rust code generator makes two passes over the AST. A scanner collects components, directives, scripts, styles, transitions, and head metadata, and a printer turns the tree into server JavaScript.
Our example page comes out as a module exporting a component factory that calls rendering helpers like createComponent, render, and renderComponent from astro/compiler-runtime. Here’s what happens to each part of the file:
- Frontmatter
importstatements stay top-level module imports, while the rest of your frontmatter code runs inside the component factory on every render. - The HTML template turns into tagged render-template data, with your JavaScript expressions kept inline inside it.
- Style blocks are extracted as CSS with a stable scope hash, and the matching scope marker gets attached to the generated HTML.
- The
Countercomponent call gets extra compiler-only props carrying its hydration directive, module path, and export name.
Alongside the generated code, the compiler returns structured metadata:
- extracted CSS blocks
- hoisted scripts
- hydrated components
- client-only components
- server-deferred components
- source maps
- head and propagation flags
- diagnostics
Astro caches all of this by file name so virtual CSS and script module requests can pull from it later. The compiler doesn’t try to resolve the client bundle on its own, it just reports what it found and leaves the module graph to Vite.
Vite builds the server and browser code
Astro 7 drives the build through Vite’s environment API in static-build.ts. Production builds use three environments:
- The prerender environment.
- The server-side rendering environment, when needed.
- The client environment.
The order matters because the client build depends on what the server builds discover. When Vite processes the prerender and server environments, transforming .astro pages uncovers every hydrated component and browser script. Astro records those discoveries in its build internals, and only then does it know the full list of client entry points.
For our example page, those client inputs include the React Counter component and React’s hydration runtime, while the build manifest includes prebuilt code for the visible directive.
Vite passes that entry list to Rolldown for the client build. If a page has no browser scripts, no application bundle gets emitted. Even when the list is empty, Astro still runs an empty client build so Vite copies your public directory into the output. Astro also sorts the client inputs before bundling so async discovery order can’t cause output chunk names to change between identical builds.
From there, Vite does its usual work: resolving imports, running transforms, splitting chunks, processing CSS, hashing assets, and reporting outputs. Astro’s plugins pull page dependencies and asset metadata out of those graphs, and deployment adapters can hook in with their own Vite plugins and build hooks.
Astro renders the page
At this point in the build, bundling has produced JavaScript modules, so we still need to turn them into HTML. Astro imports the prerender entry bundle into Node.js and passes a BuildApp instance to the default prerenderer.
For every static path, Astro constructs a standard Request and calls the app’s render() method with the matching route. Static builds and on-demand server pages run through the exact same rendering code, which means trailing slashes, redirects, cache state, sessions, middleware, actions, routes, and internationalization all work the same way.
Inside that flow, the page handler loads the built component module, creates the Astro request context, resolves any route props, and calls renderPage(). The page factory runs the frontmatter, which in our example creates the title value.
From there, the generated render template writes static HTML strings straight to the output destination and sends dynamic expressions through dedicated rendering helpers. In Astro 7, RenderTemplateResult takes a fast path for synchronous content so plain strings stream out without allocating extra buffers. As soon as it hits an async expression, it starts buffered work for later expressions so they can resolve in parallel, then flushes those buffers in source order. That queue-based setup avoids deep recursive awaits while keeping the HTML in the order you wrote it.
When rendering reaches our React Counter, it goes through renderComponent(). Astro asks the installed renderer integrations which one claims the component, and the React integration renders it to static HTML. Astro serializes the props, wraps the markup inside an <astro-island> custom element, and records the render instructions for hydration scripts. Once the page finishes, renderPage() returns a standard Response that static generation consumes as bytes.
Astro writes the HTML to dist
Next, the generatePages() function grabs every static path from the prerenderer. Simple routes already have their path in the manifest, while dynamic routes supply theirs through getStaticPaths(). Astro strips out duplicates, respects route priority, and renders pages concurrently up to your configured build concurrency.
For each path, renderPath() builds the request URL and asks the prerenderer for a Response. Redirect responses turn into tiny HTML redirect documents, and normal response bodies become byte buffers. Astro then computes the output folder and file name from build.format, the route, and your trailing-slash settings.
With the default directory format, our / route ends up at:
dist/index.html
Astro creates the destination directory, writes the HTML body to disk, and finishes up by generating optimized images and moving the built assets into place. Once that’s done, any static file server can host dist with no Astro server running.
Adapters package server-rendered sites
When a site uses on-demand routes, Astro can’t just emit static HTML files and stop there. It keeps the built server application and relies on an adapter to package it, because every hosting platform expects a different entry point and output layout.
The AstroAdapter type defines what every adapter has to provide: its name, supported features, server and preview entry points, and client configuration. An adapter can also adjust build output requirements, like requesting server output or keeping client and server files in separate directories.
During the build, the adapter receives a serialized route and asset manifest and packages Astro’s app for its target runtime. Under the hood, Astro’s core app still accepts a Request, handles routing and rendering, and returns a Response. The adapter translates platform events around that interface and prepares the files for the hosting environment.
The browser loads the interactive component
When the page reaches the browser, React’s initial button HTML is already sitting inside an <astro-island> wrapper. That wrapper holds everything the browser needs to wake the component up: the serialized props, the component chunk URL, the renderer URL, and the visible directive.
As soon as the browser connects the element to the DOM, Astro’s AstroIsland custom element runs. If the island’s children are still streaming in, it waits for them, then kicks off the selected client directive.
With client:visible, the visible directive watches the island’s children with IntersectionObserver and holds off loading the component code until at least one child becomes visible. At that point, the island dynamically imports two modules in parallel:
- the compiled React component
- the React hydration runtime
Once both modules arrive, the island revives the serialized props, collects any named slots, and passes them along with the existing server HTML to the framework hydrator. React attaches its event handlers to that markup, and the button can update its count when clicked.
Each island hydrates independently, with a parent island always finishing before a nested child island starts. After hydration succeeds, Astro removes the ssr marker from the element and emits an astro:hydrate event. Even though the server rendered the whole page, the browser only activates this one component.
What can go wrong?
Because an Astro build moves through distinct stages, the error you get usually tells you right where things broke.
Starting the build
If you’re running an unsupported Node.js version, Astro stops right in the CLI executable. A missing or invalid config stops the build during config loading, and because integration setup runs before compilation starts, an integration can reject unsupported options early too.
Routes and content
Invalid route segments fail while Astro builds the manifest, and missing static paths fail before Astro writes that route to disk. If a content loader or schema check throws an error, content synchronization stops right away so your pages never render against a partial content snapshot.
Compiling and bundling
Malformed .astro syntax gets caught by the Rust parser, which returns exact diagnostics. Astro’s wrapper turns the first compiler error into an AstroError with a file location. Style preprocessing can return several errors at once, so Astro groups multiple style failures into an aggregate error. Vite owns module resolution and bundling failures, which means a missing import stops the build before it ever reaches the page renderer.
Rendering a static page
When prerendering throws, Astro logs the failing pathname and attaches the route component if the error didn’t include an identifier. The build then fails instead of shipping an incomplete static site. Inside page rendering, Astro marks the render result as cancelled so any pending component work stops rather than generating more output.
Handling a server request
On a live server, the on-demand handler catches request-time errors and routes them through Astro’s error renderer, where a custom 500.astro page can produce the response. That failure stays contained to the single request, so the server process keeps handling later ones.
Loading an island in the browser
If fetching an island module fails in the browser, Astro retries once with a cache-busting query parameter to recover from a stale failed request. If hydration still fails, the element emits astro:hydration-error and logs the error unless your application code cancels the event. Other islands still hydrate normally, and the server-rendered HTML stays visible.
What can we self-host?
You can self-host the entire open-source path we just walked through.
For a static site, run the build and serve dist from any static file server. There’s no Astro process running in production at all.
For on-demand rendering, add the official Node adapter. In standalone mode, it builds a server at dist/server/entry.mjs that starts the HTTP server and serves your client assets. In middleware mode, it exports a handler you can mount inside Express, Fastify, or another compatible Node.js server.
If you want a working example, check out the Dockerfile I use to run Astro Node SSR. You can also swap in another official adapter for a different runtime, which changes the output packaging while leaving your .astro source model intact.
In every case, the native compiler only runs during development and builds. A static deployment doesn’t need the Rust binary or its WebAssembly fallback, and an on-demand deployment just runs the built JavaScript runtime instead of compiling .astro files on every request.
What I like about this design
A few architectural decisions in Astro are worth borrowing for your own projects.
Reuse what the compiler already found
Because the compiler returns generated code and metadata together, later plugins can reuse its lists of styles, scripts, and hydrated components right away. The Vite plugin stores compile metadata by file name so Astro doesn’t have to re-parse the same source file for every virtual module.
Find the browser code while building the server code
Astro can’t tell which files belong in the browser from file extensions alone, since a component only becomes client code when you attach a directive at its use site. Server compilation already walks those templates, so it picks up the exact client work along the way.
Use the same renderer everywhere
Static generation sends a synthetic Request through the built app, and on-demand rendering sends real incoming requests through that same app. Running routing, middleware, and page rendering through one shared model cuts down on subtle differences between output modes.
Let adapters deal with hosting
The renderer only returns a standard Response, leaving the static generator or an adapter to decide whether that becomes a file on disk or data served through a Node server, serverless function, or edge worker.
Choose interactivity per component
Putting client:visible right next to the component that needs it keeps hydration scoped to that widget instead of turning it on for the entire page. That single local choice flows through the whole build, producing metadata, a client entry, an HTML wrapper, and one browser scheduling rule.
Keep the HTML when JavaScript fails
Because framework components usually render on the server first, a hydration failure doesn’t have to erase their HTML. Even when JavaScript fails, the page still shows useful content.
Let’s build a tiny version
We can build a tiny version of this setup without writing a parser or a bundler. It’ll render a page during a build and wake up one interactive island in the browser.
Start by creating src/page.mjs with a server render function (Astro’s compiler generates a much more capable version of this):
export function render() {
return `<!doctype html>
<html lang="en">
<body>
<h1>Mini Astro</h1>
<mini-island data-component="/counter.js">
<button>Count: 0</button>
</mini-island>
<script type="module" src="/mini-island.js"></script>
</body>
</html>`
}
Next, create src/mini-island.js. This custom element waits until the browser connects it to the DOM, then loads its component module:
class MiniIsland extends HTMLElement {
async connectedCallback() {
const module = await import(this.dataset.component)
module.hydrate(this)
}
}
customElements.define('mini-island', MiniIsland)
Now add the component behavior in src/counter.js:
export function hydrate(root) {
const button = root.querySelector('button')
let count = 0
button.addEventListener('click', () => {
count += 1
button.textContent = `Count: ${count}`
})
}
Finally, create build.mjs to run the render function and write the output to dist:
import { copyFile, mkdir, writeFile } from 'node:fs/promises'
import { render } from './src/page.mjs'
await mkdir('dist', { recursive: true })
await Promise.all([
writeFile('dist/index.html', render()),
copyFile('src/mini-island.js', 'dist/mini-island.js'),
copyFile('src/counter.js', 'dist/counter.js')
])
Run the build from your terminal:
node build.mjs
Serve dist with any static HTTP server and open the page in your browser. You’ll see the server-generated HTML right away along with a working client island.
Each file has one job:
page.mjsrenders server HTMLbuild.mjssaves the rendered pagemini-island.jscontrols client loadingcounter.jsowns component behavior
This small version skips the .astro parser, the Vite module graph, CSS processing, adapters, streaming rendering, and error reporting that Astro handles in its real architecture. Even stripped down to four files, though, it follows the same loop: generate HTML on the server during the build, serve it statically when you can, and load JavaScript only where a component needs it.
Want me to talk about your product? You can sponsor this site.
Related posts about astro: