# Astro Documentation
Astro is an all-in-one web framework for building fast, content-focused websites. It uses a component-based architecture where `.astro` components render to HTML at build time or on-demand, with zero JavaScript sent to the browser by default. Astro's "Islands Architecture" allows you to add interactive UI components from any framework (React, Vue, Svelte, etc.) as isolated "islands" of interactivity while keeping the rest of the page static.
The framework excels at content-driven sites like blogs, documentation, portfolios, and marketing pages. Key features include Content Collections for type-safe content management, built-in Markdown/MDX support, automatic image optimization, server-side rendering (SSR) with adapters for various hosting platforms, and View Transitions for smooth page navigation. Astro integrates seamlessly with headless CMSs, databases, and authentication providers.
## CLI Commands
The Astro CLI provides commands for development, building, and previewing your site. The dev server uses Hot Module Replacement for instant updates.
```bash
# Create a new Astro project
npm create astro@latest
# Start development server (default port 4321)
npx astro dev
# Build for production
npx astro build
# Preview production build locally
npx astro preview
# Type-check your project
npx astro check
# Generate TypeScript types for Astro modules
npx astro sync
# Add an integration (React, Tailwind, etc.)
npx astro add react
# Common flags
npx astro dev --port 8080 --host
npx astro build --verbose
```
## Astro Components
Astro components are `.astro` files with a frontmatter script (JavaScript/TypeScript) and HTML template. They render on the server with no client-side JavaScript by default.
```astro
---
// src/components/Greeting.astro
// Component Script - runs at build time or on request
// Import other components
import Button from './Button.astro';
// Accept props with TypeScript interface
interface Props {
name: string;
greeting?: string;
}
const { name, greeting = "Hello" } = Astro.props;
// Fetch data (runs server-side only)
const response = await fetch('https://api.example.com/user');
const user = await response.json();
---
```
## Slots
Slots allow you to pass child content into components, similar to React's children prop. Named slots enable multiple content areas.
```astro
---
// src/components/Card.astro
interface Props {
title: string;
}
const { title } = Astro.props;
---
{title}
```
```astro
---
// Usage in another component
import Card from './Card.astro';
---
Custom Header Content
This goes in the default slot.
So does this paragraph.
```
## Astro Render Context (Astro Global)
The `Astro` global object provides runtime information and utilities in `.astro` files. In API endpoints, these are available on the `context` parameter.
```astro
---
// src/pages/dashboard.astro
// Access component props passed from parent
const { title } = Astro.props;
// Get URL information
const currentUrl = Astro.url; // Full URL object
const pathname = Astro.url.pathname; // e.g., "/dashboard"
const searchParams = Astro.url.searchParams.get('filter');
// Access route parameters for dynamic routes [slug].astro
const { slug } = Astro.params;
// Get the site URL from config
const siteUrl = Astro.site; // URL or undefined
// Astro version for meta tags
const generator = Astro.generator; // "Astro v5.x.x"
// Access request object (headers, method, etc.)
const userAgent = Astro.request.headers.get('user-agent');
const method = Astro.request.method;
// Get client IP (SSR only)
const clientIP = Astro.clientAddress;
// Access data from middleware
const userData = Astro.locals.user;
// Set response headers/status
Astro.response.status = 404;
Astro.response.headers.set('Cache-Control', 'max-age=3600');
// Redirect to another page
if (!userData) {
return Astro.redirect('/login', 302);
}
// Rewrite to serve different content without redirect
if (pathname === '/old-page') {
return Astro.rewrite('/new-page');
}
// i18n utilities
const locale = Astro.currentLocale;
const preferred = Astro.preferredLocale;
---
Dashboard for {userData.name}
Current path: {pathname}
```
## API Endpoints
Server endpoints handle API requests with full access to the request/response cycle. Export functions named after HTTP methods.
```typescript
// src/pages/api/users/[id].ts
import type { APIContext } from 'astro';
// Handle GET requests
export async function GET({ params, request }: APIContext) {
const { id } = params;
try {
const user = await db.users.findById(id);
if (!user) {
return new Response(JSON.stringify({ error: 'User not found' }), {
status: 404,
headers: { 'Content-Type': 'application/json' }
});
}
return new Response(JSON.stringify(user), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
return new Response(JSON.stringify({ error: 'Server error' }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
// Handle POST requests
export async function POST({ request, cookies, redirect }: APIContext) {
const data = await request.json();
// Validate input
if (!data.email || !data.name) {
return new Response(JSON.stringify({ error: 'Missing fields' }), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
const newUser = await db.users.create(data);
// Set a cookie
cookies.set('user-id', newUser.id, {
path: '/',
httpOnly: true,
secure: true,
maxAge: 60 * 60 * 24 * 7 // 1 week
});
return new Response(JSON.stringify(newUser), {
status: 201,
headers: { 'Content-Type': 'application/json' }
});
}
// Handle DELETE requests
export async function DELETE({ params }: APIContext) {
await db.users.delete(params.id);
return new Response(null, { status: 204 });
}
```
## Content Collections
Content Collections provide type-safe content management with Zod schema validation. Define collections in `src/content.config.ts`.
```typescript
// src/content.config.ts
import { defineCollection, reference } from 'astro:content';
import { glob, file } from 'astro/loaders';
import { z } from 'astro/zod';
// Blog collection from markdown files
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
updatedDate: z.coerce.date().optional(),
author: reference('authors'), // Reference another collection
tags: z.array(z.string()),
draft: z.boolean().default(false),
image: z.object({
src: z.string(),
alt: z.string(),
}).optional(),
})
});
// Authors collection from JSON
const authors = defineCollection({
loader: file('src/data/authors.json'),
schema: z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
avatar: z.string().url(),
bio: z.string().optional(),
})
});
// Remote data with custom loader
const products = defineCollection({
loader: async () => {
const response = await fetch('https://api.example.com/products');
const data = await response.json();
return data.map((product: any) => ({
id: product.sku,
...product,
}));
},
schema: z.object({
name: z.string(),
price: z.number(),
category: z.enum(['electronics', 'clothing', 'books']),
})
});
export const collections = { blog, authors, products };
```
## Querying Collections
Use `getCollection()` and `getEntry()` to query content collections with full type safety.
```astro
---
// src/pages/blog/index.astro
import { getCollection, getEntry, render } from 'astro:content';
// Get all non-draft blog posts, sorted by date
const posts = (await getCollection('blog', ({ data }) => {
return data.draft !== true;
})).sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());
// Get a single entry by ID
const featuredPost = await getEntry('blog', 'welcome-post');
---
);
}
```
## Summary
Astro is ideal for building content-rich websites where performance matters. Its zero-JS-by-default approach delivers fast page loads while still supporting interactive components through the Islands Architecture. Content Collections provide a robust, type-safe way to manage Markdown, MDX, JSON, or remote content with automatic validation and TypeScript integration. Actions simplify server-client communication with type-safe RPC calls.
Common integration patterns include using Astro for documentation sites with MDX content, blogs with markdown and frontmatter, e-commerce storefronts with SSR for dynamic pricing, and marketing sites with forms handled by Actions. The framework works seamlessly with headless CMSs (Contentful, Sanity, Strapi), databases (Prisma, Drizzle), authentication providers (Auth.js, Lucia), and deployment platforms (Vercel, Netlify, Cloudflare, Node.js servers) through its adapter system.