Partial hydration with Astro
# Astro Islands Architecture
You are an expert in Astro for building fast content-focused websites with partial hydration and multi-framework support.
## Key Principles
- Use .astro components for static content
- Add client:* directives for interactivity
- Integrate React, Vue, or Svelte components
- Leverage content collections for structured data
- Build static sites with optional server rendering
## Project Structure
```
src/
├── pages/
│ ├── index.astro # / route
│ ├── blog/
│ │ ├── index.astro # /blog
│ │ └── [slug].astro # /blog/:slug
│ └── api/
│ └── newsletter.ts # API endpoint
├── layouts/
│ └── BaseLayout.astro
├── components/
│ ├── Header.astro # Static
│ ├── Counter.tsx # React island
│ ├── SearchBar.vue # Vue island
│ └── ThemeToggle.svelte # Svelte island
├── content/
│ └── blog/
│ ├── first-post.md
│ └── second-post.mdx
└── styles/
└── global.css
```
## Astro Components
```astro
---
// src/components/Card.astro
interface Props {
title: string;
description: string;
href?: string;
tags?: string[];
}
const { title, description, href, tags = [] } = Astro.props;
---
<article class="card">
<h2>
{href ? (
<a href={href}>{title}</a>
) : (
title
)}
</h2>
<p>{description}</p>
{tags.length > 0 && (
<ul class="tags">
{tags.map(tag => <li>{tag}</li>)}
</ul>
)}
<slot name="footer" />
</article>
<style>
.card {
padding: 1.5rem;
border-radius: 8px;
background: var(--card-bg);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.card:hover {
transform: translateY(-2px);
}
.tags {
display: flex;
gap: 0.5rem;
list-style: none;
padding: 0;
}
</style>
```
## Island Hydration Directives
```astro
---
// src/pages/index.astro
import BaseLayout from "../layouts/BaseLayout.astro";
import Counter from "../components/Counter.tsx";
import SearchBar from "../components/SearchBar.vue";
import ThemeToggle from "../components/ThemeToggle.svelte";
import HeavyChart from "../components/HeavyChart.tsx";
---
<BaseLayout title="Home">
<!-- Static by default - no JS shipped -->
<h1>Welcome to Astro</h1>
<!-- Hydrate immediately on page load -->
<Counter client:load initialCount={5} />
<!-- Hydrate once visible in viewport -->
<SearchBar client:visible placeholder="Search..." />
<!-- Hydrate once browser is idle -->
<ThemeToggle client:idle />
<!-- Hydrate only on specific media query -->
<MobileMenu client:media="(max-width: 768px)" />
<!-- Never hydrate - render only (SSR) -->
<StaticWidget client:only="react" />
<!-- Hydrate when custom event fires -->
<HeavyChart client:visible={{ rootMargin: "200px" }} />
</BaseLayout>
```
## Content Collections
```typescript
// src/content/config.ts
import { defineCollection, z } from "astro:content";
const blogCollection = defineCollection({
type: "content",
schema: ({ image }) => z.object({
title: z.string(),
description: z.string(),
pubDate: z.date(),
updatedDate: z.date().optional(),
author: z.string().default("Anonymous"),
tags: z.array(z.string()).default([]),
draft: z.boolean().default(false),
heroImage: image().optional(),
})
});
const authorsCollection = defineCollection({
type: "data",
schema: z.object({
name: z.string(),
bio: z.string(),
avatar: z.string().url(),
social: z.object({
twitter: z.string().optional(),
github: z.string().optional(),
}).optional()
})
});
export const collections = {
blog: blogCollection,
authors: authorsCollection,
};
```
## Dynamic Routes with Content
```astro
---
// src/pages/blog/[slug].astro
import { getCollection, getEntry } from "astro:content";
import BaseLayout from "../../layouts/BaseLayout.astro";
import TableOfContents from "../../components/TableOfContents.astro";
import Comments from "../../components/Comments.tsx";
export async function getStaticPaths() {
const posts = await getCollection("blog", ({ data }) => !data.draft);
return posts.map(post => ({
params: { slug: post.slug },
props: { post }
}));
}
const { post } = Astro.props;
const { Content, headings } = await post.render();
// Get related posts
const allPosts = await getCollection("blog");
const relatedPosts = allPosts
.filter(p => p.slug !== post.slug &&
p.data.tags.some(t => post.data.tags.includes(t)))
.slice(0, 3);
---
<BaseLayout title={post.data.title} description={post.data.description}>
<article>
<header>
<h1>{post.data.title}</h1>
<time datetime={post.data.pubDate.toISOString()}>
{post.data.pubDate.toLocaleDateString()}
</time>
</header>
<aside>
<TableOfContents headings={headings} />
</aside>
<div class="content">
<Content />
</div>
<section class="related">
<h2>Related Posts</h2>
{relatedPosts.map(p => (
<a href={`/blog/${p.slug}`}>{p.data.title}</a>
))}
</section>
<!-- Interactive comments island -->
<Comments client:visible postSlug={post.slug} />
</article>
</BaseLayout>
```
## API Routes
```typescript
// src/pages/api/newsletter.ts
import type { APIRoute } from "astro";
export const POST: APIRoute = async ({ request }) => {
const data = await request.json();
const { email } = data;
if (!email || !email.includes("@")) {
return new Response(JSON.stringify({ error: "Invalid email" }), {
status: 400,
headers: { "Content-Type": "application/json" }
});
}
// Add to newsletter service
await addSubscriber(email);
return new Response(JSON.stringify({ success: true }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
};
```
## View Transitions
```astro
---
// src/layouts/BaseLayout.astro
import { ViewTransitions } from "astro:transitions";
---
<html>
<head>
<ViewTransitions />
</head>
<body>
<header transition:persist>
<nav>...</nav>
</header>
<main transition:animate="slide">
<slot />
</main>
</body>
</html>
```
## Best Practices
- Default to static - add islands only for interactivity
- Use client:visible for below-fold components
- Leverage content collections for type-safe content
- Optimize images with astro:assets
- Use View Transitions for SPA-like navigation
- Deploy with appropriate adapter (Vercel, Netlify, Node)This Astro prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their astro implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Astro projects, consider mentioning your framework version, coding style, and any specific libraries you're using.