--- description: This guide provides opinionated, actionable best practices for building high-performance Astro applications, focusing on zero-JavaScript by default, island architecture, and type safety. globs: **/*.{js,jsx,ts,tsx,astro} --- # Astro Best Practices Astro is a "disappearing" framework designed for shipping zero JavaScript by default, adding interactivity only where needed. Our team leverages Astro for its unparalleled performance and developer experience, especially for content-focused sites. Adhere to these guidelines to maintain a consistent, high-performing, and maintainable codebase. ## 1. Code Organization and Structure Maintain a predictable and logical file structure for easy navigation and scaling. ### 1.1 Standard Project Structure Always scaffold new projects with the official Astro starter and maintain the following structure: ``` src/ ├── components/ # Reusable UI components (Astro or UI framework islands) │ ├── ui/ # Generic, framework-agnostic components │ └── react/ # React-specific components ├── content/ # Markdown/MDX files for Content Collections ├── layouts/ # Base page layouts ├── pages/ # Top-level routes ├── styles/ # Global CSS, utility classes, Tailwind config ├── env.d.ts # Global type declarations └── astro.config.ts # Type-safe Astro configuration ``` ### 1.2 Naming Conventions - **Astro Components (`.astro`):** Use `kebab-case`. - **UI Framework Components (e.g., React `.jsx`, `.tsx`):** Use `PascalCase`. - **Pages (`.astro`):** Use `kebab-case` for file names. ❌ BAD ```astro
...
``` ```jsx // src/components/Mycard.jsx export default function Mycard() { return
...
; } ``` ✅ GOOD ```astro
...
``` ```jsx // src/components/react/MyCard.tsx export default function MyCard() { return
...
; } ``` ### 1.3 TypeScript Configuration Leverage TypeScript throughout the codebase for type safety, even in `.astro` components. **`tsconfig.json`** ```json { "extends": "astro/tsconfigs/strict", "compilerOptions": { "verbatimModuleSyntax": true, // Enforce explicit type imports "plugins": [ { "name": "@astrojs/ts-plugin" // Essential for editor support } ], "paths": { "@components/*": ["./src/components/*"], "@layouts/*": ["./src/layouts/*"], "@content/*": ["./src/content/*"], "@styles/*": ["./src/styles/*"] } }, "include": [".astro/types.d.ts", "**/*"], "exclude": ["dist"] } ``` **`astro.config.ts`** Always use a `.ts` extension for your Astro configuration for type safety. ```ts import { defineConfig } from 'astro/config'; import react from '@astrojs/react'; // Example integration export default defineConfig({ integrations: [react()], // ... other config }); ``` ## 2. Component Architecture: Astro Islands Astro's "islands" architecture is fundamental. Prioritize static HTML and introduce interactivity only when and where needed. ### 2.1 Astro Components for Static Content & Layouts Use `.astro` files for pages, layouts, and components that are primarily static or orchestrate other components. They render to HTML on the server and ship zero JavaScript by default. ```astro --- import Layout from '@layouts/Layout.astro'; import MyReactCounter from '@components/react/MyReactCounter'; ---

Hello, Astro!

This is static content.

``` ### 2.2 UI Framework Components for Interactivity (Islands) Use React, Vue, Svelte, etc., components *only* for interactive UI pieces. These are your "islands." ```tsx // src/components/react/MyReactCounter.tsx import { useState } from 'react'; export default function MyReactCounter() { const [count, setCount] = useState(0); return (

Count: {count}

); } ``` ### 2.3 Client Directives for Selective Hydration Explicitly tell Astro *when* to hydrate an island. Avoid `client:load` unless the component is critical for initial interaction. ❌ BAD (Hydrates immediately, even if not needed) ```astro ``` ✅ GOOD (Hydrates only when visible, saving bandwidth and CPU) ```astro ``` ## 3. Performance Considerations Astro's primary strength is performance. Ensure every decision aligns with shipping minimal JavaScript. ### 3.1 Zero JavaScript by Default Always assume components are static unless explicitly told otherwise. If a component doesn't need client-side JS, don't add it. ❌ BAD (Unnecessary client-side script for a simple toggle) ```astro ``` ✅ GOOD (Pure CSS or server-rendered state for simple interactions) ```astro ``` ### 3.2 Optimize Client Directives - **`client:visible`**: Default for most interactive components that appear lower on the page. - **`client:idle`**: For non-critical interactivity that can wait until the main thread is free. - **`client:load`**: Only for critical, above-the-fold interactions (e.g., main navigation, search bar). - **`client:media={query}`**: For components that only become interactive on specific screen sizes. ### 3.3 Image Optimization Use Astro's built-in image optimization for responsive, performant images. ```astro --- import { Image } from 'astro:assets'; import myImage from '@assets/my-image.jpg'; // Import local images --- A descriptive alt text ``` ## 4. Common Pitfalls and Anti-patterns Avoid these common mistakes that undermine Astro's performance benefits. ### 4.1 Over-Hydration Do not wrap entire pages or large sections in a single interactive component. This defeats the purpose of islands. ❌ BAD (Treating Astro like an SPA) ```astro ``` ✅ GOOD (Granular islands) ```astro
...
...
``` ### 4.2 Unnecessary Client-Side Scripts Avoid ` ``` ✅ GOOD (Explicitly inline or part of an island) ```astro ``` ## 5. State Management Keep state management simple and localized. Astro is not an SPA framework; most "state" should be server-rendered or localized to islands. ### 5.1 Local Island State For interactivity within an island, use the UI framework's native state management (e.g., React `useState`, Svelte stores). ```tsx // src/components/react/ThemeToggle.tsx import { useState } from 'react'; export default function ThemeToggle() { const [theme, setTheme] = useState('light'); const toggleTheme = () => setTheme(theme === 'light' ? 'dark' : 'light'); return ( ); } ``` ### 5.2 Global State (Minimal) For truly global, cross-island state (e.g., user authentication status), consider: 1. **Server-side data:** Fetch global data in the Astro component frontmatter and pass it down as props. This is the preferred method. 2. **Lightweight context/store within a shared island:** If client-side global state is unavoidable, use a minimal library like Zustand or Jotai within a single, shared UI framework component that wraps other islands. ❌ BAD (Heavy global state management for a content site) ```tsx // src/components/react/MyApp.tsx (large, complex context provider)