How to Use Astro as a Static Site Generator: A Complete Step-by-Step Guide for Building Blazing-Fast Websites
In the ever-evolving landscape of web development, static site generators (SSGs) have emerged as a powerful solution for creating fast, secure, and maintainable websites. Among the newer contenders, Astro has quickly gained attention for its unique approach to building content-driven sites. Unlike traditional frameworks that send heavy JavaScript bundles to the client, Astro leverages a concept called “Islands Architecture” to deliver zero-JS by default, only hydrating interactive components when absolutely necessary. This makes Astro an ideal choice for blogs, documentation sites, marketing pages, e-commerce storefronts, and any project where performance and SEO are top priorities. In this comprehensive tutorial, we will walk through every step of using Astro as a static site generator, from initial setup to deployment, covering best practices along the way.
Astro is not just another static site generator; it is a framework designed with modern web standards in mind. It supports multiple UI frameworks (React, Vue, Svelte, Preact, Solid, etc.) within the same project, allowing you to reuse existing components without being locked into one ecosystem. Its build process generates pure HTML and CSS, removing unnecessary JavaScript at runtime. This results in exceptionally fast load times and excellent Lighthouse scores. By the end of this guide, you will have a thorough understanding of how to leverage Astro’s capabilities to build a production-ready static site that is both developer-friendly and user-oriented.
Step 1: Setting Up Your Development Environment
Before diving into Astro, you need to ensure your development environment is ready. Astro requires Node.js version 16 or higher (LTS recommended) and a package manager such as npm, yarn, or pnpm. If you do not have Node.js installed, head over to the official website and download the latest LTS version. Once installed, verify the installation by running node --version and npm --version in your terminal. With Node.js in place, you can create a new Astro project using the official CLI. Open your terminal and run the following command:
npm create astro@latest
This command will prompt you to choose a starting template. For this tutorial, select the “Basics” template (which includes a minimal starting structure) or the “Blog” template if you want to experiment with markdown content. You can also choose to start with an empty project. After selecting the template, the CLI will ask whether you want to install dependencies and initialize a Git repository. Accept these recommendations unless you have a specific reason not to. Once the setup completes, navigate into the newly created directory and open it in your code editor:
cd my-astro-project
code .
Your project structure will look similar to this:
| Directory/File | Purpose |
|---|---|
src/ |
Source folder containing pages, components, layouts, and content |
src/pages/ |
Routes for your site (`.astro`, `.md`, `.mdx` files) |
src/components/ |
Reusable UI components (`.astro`, `.jsx`, `.vue` etc.) |
src/layouts/ |
Layout wrappers for consistent page structure |
public/ |
Static assets (images, fonts, favicon) served as-is |
astro.config.mjs |
Astro configuration file (integrations, build options) |
package.json |
Project metadata and dependencies |
Now, start the development server by running:
npm run dev
Your site will be available at http://localhost:4321. Hot module replacement is active, so any changes you make will appear instantly in the browser. You now have a complete Astro development environment ready to build upon.
Step 2: Understanding the Astro File Structure and Page Routing
One of the first things you will notice about Astro is its file‑based routing system, similar to Next.js or Gatsby. Every file inside the src/pages/ directory becomes a route on your website. For example, src/pages/index.astro corresponds to the homepage (/), and src/pages/about.astro creates an /about page. You can also use nested directories: src/pages/blog/post-1.md will be available at /blog/post-1. Astro supports both .astro files (which contain a mix of HTML, CSS, and JavaScript frontmatter) and .md/.mdx files for content—making it incredibly flexible for different types of pages.
Let’s explore the structure of a basic .astro page. Open src/pages/index.astro. You will see three sections separated by --- (three dashes): frontmatter, component script, and template. The frontmatter runs at build time; it can contain JavaScript imports, data fetching, and logic. The template is written in a JSX‑like syntax but with .astro extensions. Here is a minimal example:
---
// Frontmatter: runs once at build time
import Layout from '../layouts/Layout.astro';
const pageTitle = 'Home';
---
<Layout title={pageTitle}>
<main>
<h1>Welcome to my Astro site</h1>
<p>This page was built with zero JavaScript by default.</p>
</main>
</Layout>
Notice how the frontmatter is isolated from the template. Any variables defined inside the frontmatter can be used in the template below. If you need to include interactive components, you can import them (e.g., import MyReactComponent from '../components/MyReactComponent.jsx') and then render them in the template. Astro will automatically bundle the required JavaScript only if you add a client:* directive to the component tag, which we cover in Step 4.
Routing with Markdown files is even simpler. Create a new file src/pages/about.md with the following content:
---
title: About Us
layout: ../layouts/Layout.astro
---
# About Us
This is a markdown page. You can use all standard markdown features, including **bold**, *italic*, lists, and more.
Astro will convert the markdown to HTML and wrap it with the layout specified in the frontmatter. This seamless integration makes it ideal for content‑heavy sites like blogs and documentation.
Step 3: Creating Your First Page and Layout
Now that you understand the basics, it’s time to create a real page. We’ll build a simple “Hello World” page and a reusable layout. Start by editing the existing layout file located at src/layouts/Layout.astro. Layouts are special components that accept a <slot/> where the page content will be injected. A typical layout might include the HTML <head>, global styles, navigation, and footer. Here is an example layout:
---
export interface Props {
title: string;
}
const { title } = Astro.props;
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{title}</title>
<link rel="stylesheet" href="/styles/global.css" />
</head>
<body>
<header>
<nav>...</nav>
</header>
<slot />
<footer>...</footer>
</body>
</html>
Notice the use of TypeScript for props. You can also use JSDoc if you prefer. The <slot /> component is a placeholder for the page content. Now, update the homepage (src/pages/index.astro) to use this layout and add some personalized content:
---
import Layout from '../layouts/Layout.astro';
---
<Layout title="Home">
<article>
<h2>Hello, Astro!</h2>
<p>This is my first static page built with Astro. It's lightning fast because Astro ships zero JavaScript by default.</p>
<p>You can create content using either .astro templates or plain markdown. This flexibility makes Astro perfect for developers who love control and writers who prefer simplicity.</p>
</article>
</Layout>
If you visit http://localhost:4321, you should see your new content. The layout has been applied, and you can verify that no JavaScript is loaded (check the Network tab). That is the essence of a static site generated by Astro: pure HTML and CSS, with optional interactive islands only where needed.
To add a second page, create src/pages/contact.astro with similar structure but different content. You can also create a markdown page for a blog post. Let’s do that: create a folder src/pages/blog and inside it a file first-post.md. Add frontmatter with layout, title, and date. Astro will automatically generate a route at /blog/first-post. This demonstrates how quickly you can scaffold multiple pages.
Step 4: Using Components and the Islands Architecture
Astro’s most distinctive feature is its Islands Architecture. In a typical React or Vue app, you load a bundled JavaScript file for the entire page, even if most of the page is static. Astro reverses this: it sends only the static HTML, and for interactive components (the “islands”), it loads the minimal JavaScript needed. To make a component interactive, you add a client:* directive when including it in an Astro template. The most common directives are:
- client:load – Loads and hydrates the component immediately as soon as the page loads.
- client:idle – Hydrates the component when the browser is idle (uses
requestIdleCallback). - client:visible – Hydrates only when the component scrolls into the viewport, saving bandwidth for below‑the‑fold content.
- client:media – Hydrates only when a certain CSS media query matches (e.g., mobile view).
- client:only – Renders the component only on the client (no SSR), useful for components that rely fully on browser APIs.
Let’s create a simple interactive counter using React (you can use any framework). First, install the React integration:
npx astro add react
This command will modify the astro.config.mjs file to include the React integration and install the necessary packages. Now create a new component file src/components/Counter.jsx:
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Now, import and use this component in one of your pages, say index.astro, with a client:load directive:
---
import Layout from '../layouts/Layout.astro';
import Counter from '../components/Counter.jsx';
---
<Layout title="Home">
<article>
<h2>Interactive Island</h2>
<Counter client:load />
<p>The counter above is an island. Only the React JavaScript for that component is loaded, leaving the rest of the page as static HTML.</p>
</article>
</Layout>
When you rebuild or refresh the page, you will notice that the rest of the page remains pure HTML, while the counter component loads its own JavaScript bundle. This selective hydration drastically improves performance and Lighthouse scores, especially on content‑heavy sites with only a few interactive widgets.
You can mix components from different frameworks within the same project – Astro handles the build process seamlessly. This is a huge advantage for teams that use multiple UI libraries or are migrating from one framework to another.
Step 5: Adding Static Content with Markdown, MDX, and Collections
Astro shines when it comes to content management. You can write content in plain markdown (.md), MDX (.mdx – markdown with embedded JSX), or even JSON and YAML for data files. For blogs and documentation, markdown collections provide a powerful way to organize content with frontmatter schema and automatic pagination.
First, let’s enable MDX for richer content (embeds, interactive examples). Install the MDX integration:
npx astro add mdx
Create a new MDX file at src/pages/blog/hello-world.mdx:
---
layout: ../../layouts/Layout.astro
title: 'Hello World Blog Post'
date: 2025-02-20
---
import Counter from '../../components/Counter.jsx';
## My First MDX Post
This is a markdown post with a live React counter embedded:
<Counter client:load />
Isn't that cool? You can mix markdown and components freely.
For larger sites, you’ll want to use Astro’s content collections. Collections are defined in src/content/ and allow you to validate frontmatter with a schema, generate paginated lists, and create archive pages. To set up a blog collection, create src/content/blog and add a src/content/config.ts file with the schema. Then you can use Astro.glob() or the getCollection() utility to fetch posts. This approach is more scalable than manually placing markdown files in pages/.
For example, create src/content/config.ts:
import { defineCollection, z } from 'astro:content';
const blogCollection = defineCollection({
type: 'content', // v2.0+ uses 'content' for markdown, 'data' for JSON
schema: z.object({
title: z.string(),
date: z.date(),
tags: z.array(z.string()).optional(),
}),
});
export const collections = {
'blog': blogCollection,
};
Now move your blog posts into src/content/blog/. To render them, create a dynamic route like src/pages/blog/[...slug].astro that queries the collection and renders each post. This method gives you type safety and better performance compared to file‑based routes.
Step 6: Building and Deploying Your Static Site
Once you have developed your site, the final step is to build it for production. Astro’s build command outputs a static dist/ folder containing all HTML, CSS, and JavaScript assets. To build, run:
npm run build
The output will appear in the dist/ directory. You can preview the production build locally with:
npm run preview
This serves the dist/ folder using a local static file server, mimicking how the site will behave when deployed. Check for any broken links or missing assets.
Deployment is straightforward because Astro generates purely static files (unless you use server‑side features like astro:server). You can deploy to any static hosting provider: Netlify, Vercel, Cloudflare Pages, GitHub Pages, Amazon S3, etc. Each platform offers simple “drag and drop” or Git‑based deployment. For example, to deploy to Netlify, connect your Git repository, set the build command to npm run build, and the publish directory to dist. Netlify will automatically detect Astro and apply optimal settings.
If you need server‑side rendering (SSR) or dynamic routes with edge functions, you can enable an adapter (e.g., @astrojs/netlify for serverless functions). But for a pure static site generator use case, the default static build is ideal.
Tips and Best Practices for Using Astro
Tip 1: Optimize Images with @astrojs/image
Images are often the heaviest assets on a page. Astro provides an official integration that automatically optimizes images by resizing, converting to modern formats (WebP, AVIF), and lazy‑loading. After installing @astrojs/image, you can use the <Image /> component with src, width, height, and format attributes. This reduces bandwidth usage and improves Core Web Vitals. Always use this integration for any site with imagery.
Tip 2: Use Partial Hydration Judiciously
While Astro makes it easy to add interactivity, each interactive island comes with a small JavaScript cost. Avoid hydrating components that are not immediately needed. Use client:visible for components that appear lower on the page, client:idle for non‑critical interactivity, and client:only if server rendering is not required. Over‑using interactive components can erode Astro’s performance benefits. Review each island and ask, “Does this really need client‑side JavaScript?”
Tip 3: Leverage Scoped CSS and Global Styles
Astro automatically scopes CSS declared in <style> tags within a component or page to that component only. This prevents style leakage and makes maintenance easier. For global styles (reset, typography), include them in your layout or import a global CSS file via @import in astro.config.mjs or in the layout’s <head>. You can also use CSS preprocessors like Sass, which Astro supports with minimal configuration. For a more modern approach, consider using Tailwind CSS with the @astrojs/tailwind integration for utility‑first styling.
Frequently Asked Questions (FAQ)
Q1: How does Astro compare to Next.js and Gatsby for static sites?
Astro is more specialized for content‑driven static sites than Next.js or Gatsby, which are full‑fledged application frameworks. Next.js and Gatsby ship a certain amount of JavaScript by default and require more configuration to achieve zero‑JS output. Astro’s Islands Architecture makes it easier to build pages that are mostly static with minimal interactive islands. However, if you need a highly dynamic app with complex state management, Next.js or Gatsby might be better suited. For blogs, marketing sites, and documentation, Astro offers a lighter, faster out‑of‑the‑box experience.
Q2: Can I use a CMS with Astro?
Yes, Astro integrates well with headless CMS platforms like Sanity, Contentful, Strapi, and WordPress (via the REST API). You can fetch content at build time using JavaScript in your frontmatter and generate static pages. Astro also has a @astrojs/vercel adapter that enables on‑demand ISR (Incremental Static Regeneration) if you need to keep content updated without a full rebuild.
Q3: Does Astro support dynamic routes (e.g., pagination, tag pages)?
Absolutely. You can create dynamic routes using bracket‑based file names like src/pages/blog/[slug].astro or src/pages/tags/[tag].astro. These pages export a getStaticPaths() function that generates all routes at build time. You can combine this with content collections to automatically create pages for each blog post or tag.
Q4: Can I use Astro with TypeScript?
Yes, Astro has first‑class TypeScript support. You can write .astro files with TypeScript in the frontmatter, and you can use .ts files for components or utilities. The Astro CLI provides type checking via astro check. Using TypeScript improves code quality and helps catch errors early, especially in large projects with complex data structures.
Q5: How do I handle SEO and metadata in Astro?
Astro makes SEO straightforward because it outputs static HTML that search engines can parse easily. You can dynamically set <title>, <meta> descriptions, Open Graph tags, and structured data (JSON‑LD) within your layouts or page frontmatter. For more advanced SEO, consider using the @astropub/seo component or writing a custom set of meta helpers. Since the site is fully static, you can also easily generate a sitemap.xml using the @astrojs/sitemap integration.
Conclusion
Astro represents a paradigm shift in static site generation, prioritizing performance by shipping minimal JavaScript and leveraging the Islands Architecture. Throughout this tutorial, you have learned how to set up a development environment, understand the file‑based routing, create pages and layouts, integrate interactive components selectively, manage content with Markdown and MDX, and build and deploy a production‑ready static site. By following these steps and adopting the best practices outlined above, you can create blazing‑fast websites that excel in SEO, user experience, and developer workflow. Whether you are building a personal blog, a corporate documentation site, or a marketing landing page, Astro offers a modern, flexible, and highly performant foundation. Start experimenting with your own project today, and experience the speed and simplicity of Astro firsthand.
| Feature | Astro | Next.js (Static Export) | Gatsby | Hugo |
|---|---|---|---|---|
| Default JavaScript | Zero JS by default | React runtime bundled | React + GraphQL layer | None (pure HTML) |
| Partial Hydration | Built-in (Islands) | Custom (e.g., dynamic import) | Gatsby Script API | Not applicable |
| Multi‑framework Components | Yes (React, Vue, Svelte, etc.) | React only | React only | No (templating only) |
| Markdown/MDX Support | Native, with collections | Via plugins | Via plugins | Native (no MDX) |
| Build Speed | Fast (parallel rendering) | Moderate | Slow for large sites | Very fast |