Quick start

Introduction

Astro is a content-first web framework: file routes, .astro components, content collections, islands and a Vite-powered CLI.

Create a project

npm create astro@latest my-site
cd my-site
npm run dev

--template <name> skips the prompts; --add react installs an integration. The dev server starts on port 4321.

See: Install and setup

Project structure

.
├ src/
│ ├ pages/            # file-based routes
│ ├ components/
│ ├ layouts/
│ ├ styles/
│ └ content.config.ts # collection schemas
├ public/             # copied as-is
├ astro.config.mjs
└ tsconfig.json

Only src/pages/ is reserved; the other folders are conventions.

See: Project structure

Scripts

{
  "scripts": {
    "dev": "astro dev",
    "build": "astro build",
    "preview": "astro preview"
  }
}

build writes dist/; preview serves that folder locally.

See: CLI reference

Syntax

Frontmatter

---
const title = 'Hello, Astro'
const items = ['Dog', 'Cat']
---
<h1>{title}</h1>
<ul>
  {items.map((item) => <li>{item}</li>)}
</ul>

TypeScript between the fences runs on the server and never ships. Use class, not className; attribute values stay strings.

See: Astro syntax

Conditionals

---
const show = true
const html = '<b>Hi</b>'
---
{show && <p>Visible</p>}
<Fragment set:html={html} />

set:html skips escaping, so pass only trusted content. <>...</> is a fragment without a wrapper element.

See: Template expressions

Styles and scripts

<h1 class="title">Hi</h1>

<style>
  .title { color: teal; }
</style>

<script>
  document.querySelector('h1')
    ?.addEventListener('click', () => {})
</script>

<style> is scoped to the component; is:global opts out. <script> is bundled once per page and cannot be written as an onclick attribute.

See: Client-side scripts

Components

Create a component

src/components/Greeting.astro

---
interface Props {
  name: string
  greeting?: string
}
const { name, greeting = 'Hello' } = Astro.props
---
<h2>{greeting}, {name}!</h2>

A local Props interface is picked up automatically.

See: Astro components

Use a component

---
import Greeting from '../components/Greeting.astro'
const name = 'Ada'
---
<Greeting name={name} greeting="Hi" />
<Greeting {...{ name: 'Grace', greeting: 'Hey' }} />

Props are attributes; use braces for expression values and {...props} to spread an object.

See: Component props

Slots

src/components/Card.astro

<div class="card">
  <h2><slot name="title">Untitled</slot></h2>
  <slot />
</div>

src/pages/index.astro

---
import Card from '../components/Card.astro'
---
<Card>
  <h3 slot="title">News</h3>
  <p>Main content</p>
</Card>

Content inside <slot> is the fallback; Astro.slots.has('title') checks whether it was supplied.

See: Slots

Layouts

src/layouts/Base.astro

---
const { title } = Astro.props
---
<html>
  <head><title>{title}</title></head>
  <body><slot /></body>
</html>

A layout is a component whose <slot /> receives the page body.

See: Layouts

Markdown and MDX

Markdown pages

---
layout: ../layouts/Post.astro
title: Hello world
---
# Hello world

Regular **Markdown** content.

The layout receives frontmatter, headings, url and compiledContent() as props.

See: Markdown pages

MDX components

Install

npx astro add mdx

src/pages/post.mdx

---
title: Hello
---
import Button from '../components/Button.astro'

# {frontmatter.title}

<Button>Read more</Button>

.md cannot import components; .mdx can. Map HTML tags with export const components = { h1: Heading }.

See: MDX integration

Content collections

Define a collection

src/content.config.ts

import { defineCollection } from 'astro:content'
import { glob } from 'astro/loaders'
import { z } from 'astro/zod'

const blog = defineCollection({
  loader: glob({
    base: './src/content/blog',
    pattern: '**/*.{md,mdx}',
  }),
  schema: z.object({
    title: z.string(),
    pubDate: z.coerce.date(),
    draft: z.boolean().default(false),
  }),
})

export const collections = { blog }

The config lives at src/content.config.ts, not inside src/content/. z is Zod 4 from astro/zod.

See: Define a collection

Query entries

---
import { getCollection, getEntry } from 'astro:content'

const posts = await getCollection(
  'blog',
  ({ data }) => !data.draft
)
const first = await getEntry('blog', 'post-1')
---
<p>{first?.data.title}</p>
<ul>
  {posts.map((post) => <li>{post.data.title}</li>)}
</ul>

Entries use id, not slug; getEntry returns undefined when missing. Sort results yourself.

See: Querying collections

Render an entry

---
import { getEntry, render } from 'astro:content'

const post = await getEntry('blog', 'post-1')
if (!post) throw new Error('Post not found')
const { Content } = await render(post)
---
<Content />

render() replaces entry.render(); MDX entries accept <Content components={{ h1: Heading }} />.

See: render()

Data and env

Fetch data

---
const res = await fetch('https://api.example.com/users')
const users = await res.json()
---
<ul>
  {users.map((user) => <li>{user.name}</li>)}
</ul>

Frontmatter supports top-level await. Fetching runs at build time for static pages and per request with SSR.

See: Data fetching

Environment variables

---
const api = import.meta.env.PUBLIC_API_URL
const secret = import.meta.env.SECRET_KEY
---

Only PUBLIC_-prefixed variables reach the browser; astro:env adds typed, validated values.

See: Environment variables

Routes

File routes

src/pages/index.astro           → /
src/pages/about.astro           → /about
src/pages/blog/[slug].astro     → /blog/hello
src/pages/docs/[...path].astro  → /docs/a/b
src/pages/api/users.json.ts     → /api/users.json

_-prefixed files and folders are excluded. Route params are not URL-decoded automatically.

See: Routing

Static paths

---
import { getCollection } from 'astro:content'

export async function getStaticPaths() {
  const posts = await getCollection('blog')
  return posts.map((post) => ({
    params: { slug: post.id },
    props: { post },
  }))
}
const { post } = Astro.props
---
<h1>{post.data.title}</h1>

getStaticPaths() returns one page per param set and only runs in static mode.

See: getStaticPaths()

Endpoints

src/pages/api/hello.json.ts

import type { APIRoute } from 'astro'

export const GET: APIRoute = () =>
  new Response(JSON.stringify({ ok: true }), {
    headers: { 'Content-Type': 'application/json' },
  })

Export GET, POST, PUT and others; HEAD is derived from GET.

See: Endpoints

On-demand rendering

src/pages/login.astro

---
export const prerender = false
---

astro.config.mjs

import { defineConfig } from 'astro/config'

export default defineConfig({
  output: 'server',
  redirects: { '/old': '/new' },
})

output: 'server' needs an adapter; prerender = true pins one route back to static.

See: On-demand rendering

Styling and islands

Tailwind 4

Install

npx astro add tailwind

src/styles/global.css

@import "tailwindcss";

src/layouts/Base.astro

---
import '../styles/global.css'
---
<h1 class="text-3xl font-bold">Hi</h1>

The Vite plugin replaces @astrojs/tailwind; Tailwind 4 configuration lives in CSS.

See: Tailwind in Astro

UI frameworks

Install

npx astro add react

src/pages/index.astro

---
import Counter from '../components/Counter.jsx'
---
<Counter />
<Counter client:load />
<Counter client:visible />

Without client:*, a framework component renders to HTML with no JavaScript. Props for hydrated islands must be serializable.

See: Framework components

Islands vs components

.astro Counter.jsx client:load − 0 + .astro
Only the bordered island ships JavaScript; the rest of the page is static HTML.
ChoiceWhen to use
.astroStatic markup, layouts, data fetching
client:loadInteractive UI needed immediately
client:visibleWidget below the fold
client:only="react"Browser-only component

Prefer .astro until you need client state; each island ships its own JavaScript.

See: Islands

CLI

Common commands

CommandPurpose
astro devDev server on port 4321
astro buildBuild into dist/
astro previewServe the build locally
astro checkType-check .astro files
astro syncGenerate Astro module types
astro add reactInstall an integration
astro infoShow project setup

astro check needs @astrojs/check and TypeScript 5 or 6; TS 7 is outside its peer range. sync writes .astro/types.d.ts.

See: CLI reference

Dev flags

astro dev --port 4322 --host --open

Flags

FlagPurpose
--port <n>Port, 4321 by default
--hostListen on LAN addresses
--openOpen browser on start
--backgroundRun server in background
--forceClear the content layer cache

astro dev status, logs --follow and stop manage a background server.

See: astro dev

Scaffold and add

# scaffold a project
npm create astro@latest my-site -- --template blog
# add an integration
npx astro add mdx

There is no astro create command; astro add installs and configures integrations.

See: Integrations

Also see

0 Comments for this cheatsheet. Write yours!