# Astro Astro is a modern website build tool that combines powerful developer experience with lightweight output. It enables developers to build fast, content-focused websites using their favorite UI frameworks (React, Vue, Svelte, etc.) while shipping minimal JavaScript to the client. Astro uses an innovative architecture that renders components to HTML at build time and selectively hydrates interactive components only when needed, resulting in faster page loads and better performance. The framework provides a comprehensive ecosystem including the core build tool, CLI commands, content collections, integrations for popular frameworks and services, and specialized features like image optimization, RSS feeds, and database support. Astro's component-based architecture allows developers to mix and match different frameworks within the same project, use file-based routing, and leverage TypeScript support out of the box. The project is structured as a monorepo containing the main `astro` package, integration packages for various frameworks and platforms, utilities for RSS feeds and database management, and example projects demonstrating different use cases. ## APIs and Key Functions ### Project Initialization Creates a new Astro project with an interactive CLI that guides you through setup, template selection, and dependency installation. ```bash # Create a new Astro project with interactive prompts npm create astro@latest # Create a project in a specific directory npm create astro@latest my-astro-site # Use a specific template npm create astro@latest my-blog -- --template blog # Skip git initialization npm create astro@latest my-site -- --no-git # Skip dependency installation npm create astro@latest my-site -- --no-install ``` ### Configuration File Defines project-wide settings including integrations, build options, server configuration, and content collections. The configuration file supports TypeScript and provides type safety for all options. ```javascript // astro.config.mjs import { defineConfig } from 'astro/config'; import react from '@astrojs/react'; import tailwind from '@astrojs/tailwind'; import sitemap from '@astrojs/sitemap'; export default defineConfig({ // Site URL for canonical URLs and sitemaps site: 'https://example.com', // Base path for deployment base: '/my-site', // Output mode: 'static' for SSG, 'server' for SSR, 'hybrid' for mixed output: 'static', // Server configuration for dev and preview server: { port: 3000, host: true }, // Build configuration build: { format: 'directory', // 'file' or 'directory' client: './dist/client', server: './dist/server' }, // Add integrations integrations: [ react(), tailwind(), sitemap() ], // Vite configuration passthrough vite: { plugins: [], resolve: { alias: { '@': './src' } } } }); ``` ### Development Server Starts a local development server with Hot Module Replacement (HMR) for rapid development iteration. The dev server watches for file changes and automatically updates the browser. ```javascript // JavaScript API usage import { dev } from 'astro'; const server = await dev({ root: './my-project', server: { port: 4321, host: 'localhost' } }); // Server provides: // - server.address: { address: string, port: number } // - server.stop(): Promise - Stop the server // - server.watcher: FSWatcher - File system watcher // - server.handle(req, res) - Request handler // Stop the server when done await server.stop(); ``` ```bash # CLI usage - start development server astro dev # Use custom port astro dev --port 3000 # Use custom host astro dev --host 0.0.0.0 ``` ### Preview Server Serves the built static site locally for testing before deployment. Useful for verifying the production build works correctly. ```javascript // JavaScript API usage import { preview } from 'astro'; const server = await preview({ root: './my-project', server: { port: 4321, host: 'localhost' } }); // Server provides the same interface as dev server console.log(`Preview server running at http://localhost:${server.address.port}`); // Stop when done await server.stop(); ``` ```bash # CLI usage - preview production build astro preview # Custom port astro preview --port 8080 ``` ### Type Generation and Sync Generates TypeScript types for content collections and environment variables, setting up type inference for Astro modules. ```javascript // JavaScript API usage import { sync } from 'astro'; await sync({ root: './my-project' }); ``` ```bash # CLI usage - generate types for content collections astro sync # Typically run before type checking astro sync && tsc --noEmit ``` ### Content Collections Defines type-safe content collections with schema validation, supporting markdown, MDX, and JSON files. Collections provide a structured way to manage blog posts, documentation, products, etc. ```typescript // src/content.config.ts import { defineCollection, z } from 'astro:content'; import { glob } from 'astro/loaders'; // Define a blog collection const blog = defineCollection({ // Use glob loader for markdown/MDX files loader: glob({ base: './src/content/blog', pattern: '**/*.{md,mdx}' }), // Schema for frontmatter validation schema: ({ image }) => z.object({ title: z.string(), description: z.string(), pubDate: z.coerce.date(), updatedDate: z.coerce.date().optional(), heroImage: image().optional(), tags: z.array(z.string()).default([]), draft: z.boolean().default(false) }) }); // Define a documentation collection const docs = defineCollection({ loader: glob({ base: './src/content/docs', pattern: '**/*.md' }), schema: z.object({ title: z.string(), description: z.string(), order: z.number(), category: z.enum(['guide', 'reference', 'tutorial']) }) }); export const collections = { blog, docs }; ``` ```typescript // src/pages/blog/[...slug].astro - Using content collections --- import { getCollection, getEntry } from 'astro:content'; import Layout from '../../layouts/BlogLayout.astro'; // Get all blog entries export async function getStaticPaths() { const blogEntries = await getCollection('blog', ({ data }) => { return data.draft !== true; // Filter out drafts }); return blogEntries.map(entry => ({ params: { slug: entry.id }, props: { entry } })); } const { entry } = Astro.props; const { Content } = await entry.render(); ---

{entry.data.title}

``` ### Component Rendering with Container API Enables server-side rendering of Astro components in isolation, useful for testing, email generation, and dynamic server-side rendering scenarios. ```javascript // Server-side component rendering import { experimental_AstroContainer as AstroContainer } from 'astro/container'; import Card from '../src/components/Card.astro'; // Create a container instance const container = await AstroContainer.create({ streaming: false, renderers: [], // Add framework renderers if needed }); // Render component to string const html = await container.renderToString(Card, { props: { title: 'Hello World', content: 'This is a card component' }, slots: { default: '

Slot content here

' }, request: new Request('https://example.com/test') }); console.log(html); // '
...
' // Render to Response object const response = await container.renderToResponse(Card, { props: { title: 'Test' } }); console.log(response.status); // 200 const text = await response.text(); ``` ```javascript // With React integration import reactRenderer from '@astrojs/react/server.js'; import ReactComponent from '../src/components/ReactComponent.jsx'; const container = await AstroContainer.create(); // Add server renderer container.addServerRenderer({ renderer: reactRenderer }); // Add client renderer for client: directives container.addClientRenderer({ name: '@astrojs/react', entrypoint: '@astrojs/react/client.js' }); const html = await container.renderToString(ReactComponent, { props: { message: 'Hello from React' } }); ``` ### React Integration Adds support for React components in Astro projects, including server-side rendering and optional client-side hydration. ```javascript // astro.config.mjs import { defineConfig } from 'astro/config'; import react from '@astrojs/react'; export default defineConfig({ integrations: [ react({ // Include React 17 compatibility include: ['**/react/*'], // Exclude specific files exclude: ['**/node_modules/**'] }) ] }); ``` ```jsx // src/components/Counter.jsx import { useState } from 'react'; export default function Counter({ initial = 0 }) { const [count, setCount] = useState(initial); return (

Count: {count}

); } ``` ```astro --- import Layout from '../layouts/Layout.astro'; import Counter from '../components/Counter.jsx'; --- ``` ### MDX Integration Enables writing pages and content in MDX format, combining Markdown with JSX components for rich, interactive documentation. ```javascript // astro.config.mjs import { defineConfig } from 'astro/config'; import mdx from '@astrojs/mdx'; export default defineConfig({ integrations: [ mdx({ // Extend markdown config syntaxHighlight: 'shiki', shikiConfig: { theme: 'dracula' }, remarkPlugins: [], rehypePlugins: [], // Optimize images in MDX optimize: true }) ] }); ``` ```mdx --- title: About Us layout: ../layouts/Layout.astro --- import Button from '../components/Button.astro'; import { Chart } from '../components/Chart.jsx'; # {frontmatter.title} This is **MDX** content with components! ## Features - Mix Markdown and JSX - Import components - Use frontmatter ``` ### RSS Feed Generation Creates RSS/Atom feeds for blogs and content sites, with support for custom styling and content serialization. ```typescript // src/pages/rss.xml.ts import rss from '@astrojs/rss'; import { getCollection } from 'astro:content'; import sanitizeHtml from 'sanitize-html'; import MarkdownIt from 'markdown-it'; const parser = new MarkdownIt(); export async function GET(context) { const blog = await getCollection('blog', ({ data }) => { return data.draft !== true; }); return rss({ title: 'My Astro Blog', description: 'A blog about web development', site: context.site, // Add items from content collection items: blog.map((post) => ({ title: post.data.title, description: post.data.description, pubDate: post.data.pubDate, link: `/blog/${post.id}/`, // Include full content in feed content: sanitizeHtml(parser.render(post.body), { allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']) }), // Custom data customData: `${post.data.author}`, categories: post.data.tags })), // Custom XML stylesheet stylesheet: '/rss-styles.xsl', // Atom feed support xmlns: { atom: 'http://www.w3.org/2005/Atom' } }); } ``` ### Database Integration (Astro DB) Provides a libSQL-powered database with type-safe queries using Drizzle ORM, perfect for storing structured data in Astro projects. ```typescript // db/config.ts import { defineDb, defineTable, column } from 'astro:db'; const Comment = defineTable({ columns: { id: column.number({ primaryKey: true }), author: column.text(), body: column.text(), postId: column.text(), createdAt: column.date({ default: new Date() }) }, indexes: { postIdx: { on: ['postId'], unique: false } } }); const User = defineTable({ columns: { id: column.number({ primaryKey: true }), email: column.text({ unique: true }), name: column.text(), role: column.text({ default: 'user' }) } }); export default defineDb({ tables: { Comment, User } }); ``` ```typescript // src/pages/api/comments.ts import { db, Comment, eq } from 'astro:db'; export async function GET({ params }) { const postId = params.postId; // Query comments for a post const comments = await db .select() .from(Comment) .where(eq(Comment.postId, postId)) .orderBy(Comment.createdAt); return new Response(JSON.stringify(comments), { headers: { 'Content-Type': 'application/json' } }); } export async function POST({ request }) { const data = await request.json(); // Insert new comment with validation const [newComment] = await db .insert(Comment) .values({ author: data.author, body: data.body, postId: data.postId }) .returning(); return new Response(JSON.stringify(newComment), { status: 201, headers: { 'Content-Type': 'application/json' } }); } ``` ```bash # CLI commands for database management astro db push --remote # Push schema to production astro db verify # Verify local schema astro db sync # Generate types from schema ``` ### Image Optimization Optimizes images at build time with automatic format conversion, resizing, and responsive image generation. ```astro --- // src/pages/gallery.astro import { Image, Picture, getImage } from 'astro:assets'; import heroImage from '../assets/hero.jpg'; --- Hero image Remote image ``` ```typescript // Programmatic image optimization import { getImage } from 'astro:assets'; import sourceImage from '../assets/photo.png'; const optimizedImage = await getImage({ src: sourceImage, width: 400, height: 300, format: 'webp', quality: 85 }); // Use optimizedImage.src in your markup const imageUrl = optimizedImage.src; const imageAttrs = optimizedImage.attributes; ``` ### Vite Configuration Extension Extends Astro's underlying Vite configuration for advanced customization of the build process. ```javascript // astro.config.mjs import { defineConfig } from 'astro/config'; import { getViteConfig } from 'astro/config'; // Get Vite config from Astro export default defineConfig({ vite: getViteConfig({ plugins: [], optimizeDeps: { include: ['lodash-es'], exclude: ['some-large-dep'] }, build: { rollupOptions: { output: { manualChunks: { vendor: ['react', 'react-dom'] } } } }, server: { fs: { allow: ['..'] } } }) }); ``` ## Use Cases and Integration Patterns Astro excels at building content-focused websites where performance is critical, including blogs, documentation sites, marketing pages, and e-commerce storefronts. Its islands architecture makes it ideal for mostly static sites with pockets of interactivity, delivering optimal performance by shipping minimal JavaScript. The framework's zero-JS-by-default approach means developers can add interactivity only where needed using `client:*` directives, resulting in significantly faster page loads compared to traditional SPA frameworks. Astro integrates seamlessly with existing content workflows through its content collections API, supporting markdown, MDX, and remote data sources while providing full TypeScript type safety. For integration patterns, Astro's adapter system enables deployment to various platforms including Vercel, Netlify, Cloudflare, and Node.js servers, with each adapter optimizing the build output for its target platform. The framework supports both static site generation (SSG) and server-side rendering (SSR), with a hybrid mode that allows mixing strategies per route. Developers can combine multiple UI frameworks in a single project, using React for complex interactive components while leveraging Svelte or Vue for simpler widgets. The Container API enables advanced patterns like component testing, email template rendering, and dynamic page generation at runtime, making Astro flexible enough for both build-time and runtime rendering scenarios.