name: astro-patterns
description: Astro best practices, routing patterns, component architecture, and static site generation techniques. Use when building Astro websites, setting up routing, designing component architecture, configuring static site generation, optimizing build performance, implementing content strategies, or when user mentions Astro patterns, routing, component design, SSG, static sites, or Astro best practices.
allowed-tools: - Read
- Write
- Edit
- Bash
- Glob
- Grep
Astro Patterns
Comprehensive best practices, routing patterns, component architecture, and static site generation techniques for building high-performance Astro websites.
Overview
This skill provides:
- File-based routing patterns and advanced routing configurations
- Component architecture following islands architecture principles
- Layout systems with nested layouts and slot patterns
- Content strategies for blogs, documentation, and marketing sites
- Static site generation optimization techniques
- Build performance tuning and bundle optimization
- SEO and performance best practices
Setup Scripts
Core Setup Scripts
- scripts/setup-routing.sh - Initialize routing structure and conventions
- scripts/setup-components.sh - Scaffold component directory structure
- scripts/setup-layouts.sh - Create layout hierarchy
- scripts/validate-structure.sh - Validate Astro project structure
- scripts/optimize-build.sh - Apply build optimization configurations
Utility Scripts
- scripts/generate-route.sh - Generate new route with layouts
- scripts/generate-page.sh - Create new page with best practices
- scripts/analyze-performance.sh - Analyze build and runtime performance
- scripts/generate-sitemap.sh - Generate sitemap configuration
Templates
Routing Templates
- templates/routing/basic-page.astro - Standard page with layouts
- templates/routing/dynamic-route.astro - Dynamic route with getStaticPaths
- templates/routing/api-endpoint.ts - API endpoint handler
- templates/routing/middleware.ts - Route middleware configuration
- templates/routing/redirect-config.ts - Redirect rules
- templates/routing/404-page.astro - Custom 404 error page
Component Templates
- templates/components/base-component.astro - Basic Astro component
- templates/components/island-wrapper.astro - Framework component wrapper
- templates/components/slot-component.astro - Component with named slots
- templates/components/props-component.astro - Type-safe props pattern
- templates/components/async-component.astro - Component with data fetching
- templates/components/component-collection.astro - Reusable component set
Layout Templates
- templates/layouts/base-layout.astro - Root layout with SEO
- templates/layouts/nested-layout.astro - Nested layout pattern
- templates/layouts/blog-layout.astro - Blog post layout
- templates/layouts/docs-layout.astro - Documentation layout
- templates/layouts/marketing-layout.astro - Marketing page layout
- templates/layouts/layout-with-sidebar.astro - Layout with navigation sidebar
Content Templates
- templates/content/blog-post.md - Blog post with frontmatter
- templates/content/documentation-page.md - Docs page structure
- templates/content/landing-page.astro - Landing page pattern
- templates/content/case-study.astro - Case study template
Build Templates
- templates/build/astro.config.ts - Full Astro configuration
- templates/build/tsconfig.json - TypeScript configuration
- templates/build/env.d.ts - Environment types
- templates/build/image-optimization.ts - Image optimization config
Examples
- examples/basic-routing.md - File-based routing examples
- examples/dynamic-routes.md - Dynamic route patterns with getStaticPaths
- examples/component-architecture.md - Component organization patterns
- examples/layout-hierarchy.md - Nested layout examples
- examples/content-collections-usage.md - Content collections integration
- examples/build-optimization.md - Build performance techniques
- examples/seo-patterns.md - SEO and metadata best practices
- examples/api-routes.md - API endpoint patterns
Instructions
Phase 1: Project Structure Setup
Validate Existing Structure
# Check project structure
bash scripts/validate-structure.sh
Setup Core Directories
# Initialize routing structure
bash scripts/setup-routing.sh
# Setup component architecture
bash scripts/setup-components.sh
# Create layout hierarchy
bash scripts/setup-layouts.sh
Configure Astro
- Read: templates/build/astro.config.ts
- Configure integrations, output mode, build settings
- Setup path aliases and base URL
Phase 2: Routing Architecture
File-Based Routing
- Read: examples/basic-routing.md
- Follow directory structure conventions
- Use index.astro for default routes
- Name files with kebab-case
Dynamic Routes
- Read: examples/dynamic-routes.md
- Read: templates/routing/dynamic-route.astro
- Implement getStaticPaths for SSG
- Use [param] syntax for dynamic segments
- Handle 404 cases with custom error pages
Generate New Routes
# Create new route with scaffolding
bash scripts/generate-route.sh /blog/[slug] --layout blog
# Create standard page
bash scripts/generate-page.sh /about --layout marketing
API Endpoints
- Read: templates/routing/api-endpoint.ts
- Read: examples/api-routes.md
- Create endpoints in pages/api/
- Return Response objects
- Handle different HTTP methods
Phase 3: Component Architecture
Component Organization
- Read: examples/component-architecture.md
- Structure: components/{common,layout,ui,features}
- Use clear naming conventions
- Separate presentational from container components
Create Components
- Read: templates/components/base-component.astro
- Read: templates/components/props-component.astro
- Define TypeScript interfaces for props
- Use slots for composition
- Export component types
Async Data Fetching
- Read: templates/components/async-component.astro
- Fetch data in component frontmatter
- Handle loading and error states
- Cache responses when appropriate
Islands Architecture
- Read: templates/components/island-wrapper.astro
- Use framework components selectively
- Apply appropriate client directives
- Minimize client-side JavaScript
Phase 4: Layout System
Base Layout
- Read: templates/layouts/base-layout.astro
- Include global styles, meta tags, scripts
- Setup SEO defaults
- Add accessibility features
Nested Layouts
- Read: examples/layout-hierarchy.md
- Read: templates/layouts/nested-layout.astro
- Create layout chains: base → section → page
- Use layout prop pattern
- Pass data through layout hierarchy
Content-Specific Layouts
- Read: templates/layouts/blog-layout.astro
- Read: templates/layouts/docs-layout.astro
- Create specialized layouts for content types
- Add navigation, TOC, breadcrumbs
- Include content metadata
Phase 5: Content Strategy
Content Collections
- Read: examples/content-collections-usage.md
- Define schemas in src/content/config.ts
- Use type-safe content queries
- Implement content validation
Blog Architecture
- Read: templates/content/blog-post.md
- Setup blog collection with frontmatter
- Create blog index with pagination
- Add RSS feed generation
- Implement tag/category filtering
Documentation Sites
- Read: templates/content/documentation-page.md
- Create hierarchical navigation
- Add search functionality
- Include code syntax highlighting
- Generate table of contents
Phase 6: Build Optimization
Configure Build Settings
- Read: templates/build/astro.config.ts
- Read: examples/build-optimization.md
- Set output mode (static, server, hybrid)
- Configure build splitting
- Enable compression
Apply Optimizations
# Run optimization script
bash scripts/optimize-build.sh
# Analyze performance
bash scripts/analyze-performance.sh
Image Optimization
- Read: templates/build/image-optimization.ts
- Use Astro Image component
- Configure image formats (WebP, AVIF)
- Implement responsive images
- Add lazy loading
Bundle Optimization
- Analyze bundle sizes
- Split vendor chunks
- Implement code splitting
- Minimize CSS and JavaScript
- Remove unused dependencies
Phase 7: SEO and Performance
SEO Setup
- Read: examples/seo-patterns.md
- Add meta tags to base layout
- Generate sitemap and robots.txt
- Implement structured data
- Add Open Graph and Twitter cards
Generate Sitemap
bash scripts/generate-sitemap.sh
Performance Testing
- Test with Lighthouse
- Verify Core Web Vitals
- Check page load times
- Validate accessibility scores
Best Practices
Routing
- File Organization: Group related routes in directories
- Index Files: Use index.astro for directory default pages
- Dynamic Parameters: Name params clearly: [postSlug] not [slug]
- 404 Handling: Always provide custom 404.astro page
- Redirects: Use Astro redirects, not client-side navigation
Component Design
- Single Responsibility: Each component does one thing well
- Composition: Use slots and props for flexibility
- Type Safety: Define TypeScript interfaces for all props
- Async Loading: Fetch data in component frontmatter
- Minimal Client JS: Keep components static by default
Layout Architecture
- Layout Hierarchy: Base → Section → Page layouts
- Consistent Structure: All layouts extend base layout
- Slot Usage: Use named slots for flexible content areas
- SEO in Base: Put SEO defaults in base layout
- Performance: Avoid heavy computation in layouts
Content Management
- Content Collections: Use for all structured content
- Frontmatter Schema: Define strict schemas for validation
- Type Safety: Generate TypeScript types from schemas
- Markdown: Use remark/rehype plugins for enhancements
- Asset Management: Store assets in src/ for optimization
Build Performance
- Static by Default: Generate static HTML when possible
- Code Splitting: Split bundles by route
- Image Optimization: Always use Astro Image
- Prefetching: Prefetch critical routes
- Caching: Configure appropriate cache headers
SEO
- Semantic HTML: Use proper heading hierarchy
- Meta Tags: Include title, description, OG tags
- Sitemap: Generate and submit to search engines
- Structured Data: Add JSON-LD for rich results
- Performance: Fast sites rank better
Common Patterns
Pattern 1: Dynamic Blog Route
---
// src/pages/blog/[slug].astro
import { getCollection } from 'astro:content';
import BlogLayout from '@/layouts/BlogLayout.astro';
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map(post => ({
params: { slug: post.slug }
props: { post }
}));
}
const { post } = Astro.props;
const { Content } = await post.render();
---
<BlogLayout title={post.data.title} description={post.data.description}>
<Content />
</BlogLayout>
Pattern 2: Nested Layout Chain
---
// src/layouts/BlogLayout.astro
import BaseLayout from './BaseLayout.astro';
interface Props {
title: string;
description: string;
}
const { title, description } = Astro.props;
---
<BaseLayout title={title} description={description}>
<div class="blog-container">
<aside class="sidebar">
<!-- Blog sidebar -->
</aside>
<main class="content">
<slot />
</main>
</div>
</BaseLayout>
Pattern 3: Type-Safe Component Props
---
// src/components/Card.astro
export interface Props {
title: string;
description?: string;
href?: string;
variant?: 'default' | 'featured' | 'compact';
}
const {
title
description
href
variant = 'default'
} = Astro.props;
---
<div class={`card card-${variant}`}>
<h3>{title}</h3>
{description && <p>{description}</p>}
{href && <a href={href}>Read more</a>}
</div>
Pattern 4: API Endpoint
// src/pages/api/posts.ts
import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';
export const GET: APIRoute = async ({ request }) => {
const posts = await getCollection('blog');
return new Response(JSON.stringify(posts), {
status: 200
headers: {
'Content-Type': 'application/json'
'Cache-Control': 'public, max-age=3600'
}
});
};
Pattern 5: Optimized Image Usage
---
import { Image } from 'astro:assets';
import heroImage from '@/assets/hero.jpg';
---
<Image
src={heroImage}
alt="Hero image"
width={1200}
height={600}
format="webp"
loading="lazy"
quality={80}
/>
Troubleshooting
Routes Not Generating
Problem: Dynamic routes not building
Solution:
- Check getStaticPaths returns array of {params, props}
- Verify params match route file name: [slug].astro needs params.slug
- Ensure all content is available at build time
- Check for async issues in getStaticPaths
Build Performance Issues
Problem: Slow build times
Solution:
- Run:
bash scripts/analyze-performance.sh
- Check for unnecessary data fetching
- Optimize images before importing
- Review large dependencies
- Enable build parallelization
Component Not Rendering
Problem: Component shows blank or errors
Solution:
- Check component imports use correct path aliases
- Verify props interface matches usage
- Check for SSR-incompatible code (window, document)
- Review error messages in build output
Layout Not Applied
Problem: Layout styles or structure missing
Solution:
- Verify layout prop is passed correctly
- Check layout file exports default component
- Ensure base layout includes global styles
- Review slot placement in layout chain
SEO Tags Not Appearing
Problem: Meta tags missing from pages
Solution:
- Check base layout includes SEO component
- Verify props passed through layout hierarchy
- Inspect generated HTML for meta tags
- Ensure head slot is used correctly
Related Skills
- component-integration: For React, MDX, and Tailwind integration
- content-collections: Deep dive into content management
- performance-optimization: Advanced performance tuning
Requirements
- Node.js 18+
- Astro 4.0+
- TypeScript 5.0+
- Recommended: pnpm or yarn
Plugin: website-builder
Version: 1.0.0
1---2name: astro-patterns3description: Astro best practices, routing patterns, component architecture, and static site generation techniques. Use when building Astro websites, setting up routing, designing component architecture, configuri4---5
6---
7name: astro-patterns
8description: Astro best practices, routing patterns, component architecture, and static site generation techniques. Use when building Astro websites, setting up routing, designing component architecture, configuring static site generation, optimizing build performance, implementing content strategies, or when user mentions Astro patterns, routing, component design, SSG, static sites, or Astro best practices.
9allowed-tools: - Read
10 - Write
11 - Edit
12 - Bash
13 - Glob
14 - Grep
15---
16
17# Astro Patterns
18
19Comprehensive best practices, routing patterns, component architecture, and static site generation techniques for building high-performance Astro websites.
20
21## Overview
22
23This skill provides:
24- File-based routing patterns and advanced routing configurations
25- Component architecture following islands architecture principles
26- Layout systems with nested layouts and slot patterns
27- Content strategies for blogs, documentation, and marketing sites
28- Static site generation optimization techniques
29- Build performance tuning and bundle optimization
30- SEO and performance best practices
31
32## Setup Scripts
33
34### Core Setup Scripts
35
361. **scripts/setup-routing.sh** - Initialize routing structure and conventions
372. **scripts/setup-components.sh** - Scaffold component directory structure
383. **scripts/setup-layouts.sh** - Create layout hierarchy
394. **scripts/validate-structure.sh** - Validate Astro project structure
405. **scripts/optimize-build.sh** - Apply build optimization configurations
41
42### Utility Scripts
43
446. **scripts/generate-route.sh** - Generate new route with layouts
457. **scripts/generate-page.sh** - Create new page with best practices
468. **scripts/analyze-performance.sh** - Analyze build and runtime performance
479. **scripts/generate-sitemap.sh** - Generate sitemap configuration
48
49## Templates
50
51### Routing Templates
52
531. **templates/routing/basic-page.astro** - Standard page with layouts
542. **templates/routing/dynamic-route.astro** - Dynamic route with getStaticPaths
553. **templates/routing/api-endpoint.ts** - API endpoint handler
564. **templates/routing/middleware.ts** - Route middleware configuration
575. **templates/routing/redirect-config.ts** - Redirect rules
586. **templates/routing/404-page.astro** - Custom 404 error page
59
60### Component Templates
61
627. **templates/components/base-component.astro** - Basic Astro component
638. **templates/components/island-wrapper.astro** - Framework component wrapper
649. **templates/components/slot-component.astro** - Component with named slots
6510. **templates/components/props-component.astro** - Type-safe props pattern
6611. **templates/components/async-component.astro** - Component with data fetching
6712. **templates/components/component-collection.astro** - Reusable component set
68
69### Layout Templates
70
7113. **templates/layouts/base-layout.astro** - Root layout with SEO
7214. **templates/layouts/nested-layout.astro** - Nested layout pattern
7315. **templates/layouts/blog-layout.astro** - Blog post layout
7416. **templates/layouts/docs-layout.astro** - Documentation layout
7517. **templates/layouts/marketing-layout.astro** - Marketing page layout
7618. **templates/layouts/layout-with-sidebar.astro** - Layout with navigation sidebar
77
78### Content Templates
79
8019. **templates/content/blog-post.md** - Blog post with frontmatter
8120. **templates/content/documentation-page.md** - Docs page structure
8221. **templates/content/landing-page.astro** - Landing page pattern
8322. **templates/content/case-study.astro** - Case study template
84
85### Build Templates
86
8723. **templates/build/astro.config.ts** - Full Astro configuration
8824. **templates/build/tsconfig.json** - TypeScript configuration
8925. **templates/build/env.d.ts** - Environment types
9026. **templates/build/image-optimization.ts** - Image optimization config
91
92## Examples
93
941. **examples/basic-routing.md** - File-based routing examples
952. **examples/dynamic-routes.md** - Dynamic route patterns with getStaticPaths
963. **examples/component-architecture.md** - Component organization patterns
974. **examples/layout-hierarchy.md** - Nested layout examples
985. **examples/content-collections-usage.md** - Content collections integration
996. **examples/build-optimization.md** - Build performance techniques
1007. **examples/seo-patterns.md** - SEO and metadata best practices
1018. **examples/api-routes.md** - API endpoint patterns
102
103## Instructions
104
105### Phase 1: Project Structure Setup
106
1071. **Validate Existing Structure**
108 ```bash
109 # Check project structure
110 bash scripts/validate-structure.sh
111 ```
112
1132. **Setup Core Directories**
114 ```bash
115 # Initialize routing structure
116 bash scripts/setup-routing.sh
117
118 # Setup component architecture
119 bash scripts/setup-components.sh
120
121 # Create layout hierarchy
122 bash scripts/setup-layouts.sh
123 ```
124
1253. **Configure Astro**
126 - Read: templates/build/astro.config.ts
127 - Configure integrations, output mode, build settings
128 - Setup path aliases and base URL
129
130### Phase 2: Routing Architecture
131
1321. **File-Based Routing**
133 - Read: examples/basic-routing.md
134 - Follow directory structure conventions
135 - Use index.astro for default routes
136 - Name files with kebab-case
137
1382. **Dynamic Routes**
139 - Read: examples/dynamic-routes.md
140 - Read: templates/routing/dynamic-route.astro
141 - Implement getStaticPaths for SSG
142 - Use [param] syntax for dynamic segments
143 - Handle 404 cases with custom error pages
144
1453. **Generate New Routes**
146 ```bash
147 # Create new route with scaffolding
148 bash scripts/generate-route.sh /blog/[slug] --layout blog
149
150 # Create standard page
151 bash scripts/generate-page.sh /about --layout marketing
152 ```
153
1544. **API Endpoints**
155 - Read: templates/routing/api-endpoint.ts
156 - Read: examples/api-routes.md
157 - Create endpoints in pages/api/
158 - Return Response objects
159 - Handle different HTTP methods
160
161### Phase 3: Component Architecture
162
1631. **Component Organization**
164 - Read: examples/component-architecture.md
165 - Structure: components/{common,layout,ui,features}
166 - Use clear naming conventions
167 - Separate presentational from container components
168
1692. **Create Components**
170 - Read: templates/components/base-component.astro
171 - Read: templates/components/props-component.astro
172 - Define TypeScript interfaces for props
173 - Use slots for composition
174 - Export component types
175
1763. **Async Data Fetching**
177 - Read: templates/components/async-component.astro
178 - Fetch data in component frontmatter
179 - Handle loading and error states
180 - Cache responses when appropriate
181
1824. **Islands Architecture**
183 - Read: templates/components/island-wrapper.astro
184 - Use framework components selectively
185 - Apply appropriate client directives
186 - Minimize client-side JavaScript
187
188### Phase 4: Layout System
189
1901. **Base Layout**
191 - Read: templates/layouts/base-layout.astro
192 - Include global styles, meta tags, scripts
193 - Setup SEO defaults
194 - Add accessibility features
195
1962. **Nested Layouts**
197 - Read: examples/layout-hierarchy.md
198 - Read: templates/layouts/nested-layout.astro
199 - Create layout chains: base → section → page
200 - Use layout prop pattern
201 - Pass data through layout hierarchy
202
2033. **Content-Specific Layouts**
204 - Read: templates/layouts/blog-layout.astro
205 - Read: templates/layouts/docs-layout.astro
206 - Create specialized layouts for content types
207 - Add navigation, TOC, breadcrumbs
208 - Include content metadata
209
210### Phase 5: Content Strategy
211
2121. **Content Collections**
213 - Read: examples/content-collections-usage.md
214 - Define schemas in src/content/config.ts
215 - Use type-safe content queries
216 - Implement content validation
217
2182. **Blog Architecture**
219 - Read: templates/content/blog-post.md
220 - Setup blog collection with frontmatter
221 - Create blog index with pagination
222 - Add RSS feed generation
223 - Implement tag/category filtering
224
2253. **Documentation Sites**
226 - Read: templates/content/documentation-page.md
227 - Create hierarchical navigation
228 - Add search functionality
229 - Include code syntax highlighting
230 - Generate table of contents
231
232### Phase 6: Build Optimization
233
2341. **Configure Build Settings**
235 - Read: templates/build/astro.config.ts
236 - Read: examples/build-optimization.md
237 - Set output mode (static, server, hybrid)
238 - Configure build splitting
239 - Enable compression
240
2412. **Apply Optimizations**
242 ```bash
243 # Run optimization script
244 bash scripts/optimize-build.sh
245
246 # Analyze performance
247 bash scripts/analyze-performance.sh
248 ```
249
2503. **Image Optimization**
251 - Read: templates/build/image-optimization.ts
252 - Use Astro Image component
253 - Configure image formats (WebP, AVIF)
254 - Implement responsive images
255 - Add lazy loading
256
2574. **Bundle Optimization**
258 - Analyze bundle sizes
259 - Split vendor chunks
260 - Implement code splitting
261 - Minimize CSS and JavaScript
262 - Remove unused dependencies
263
264### Phase 7: SEO and Performance
265
2661. **SEO Setup**
267 - Read: examples/seo-patterns.md
268 - Add meta tags to base layout
269 - Generate sitemap and robots.txt
270 - Implement structured data
271 - Add Open Graph and Twitter cards
272
2732. **Generate Sitemap**
274 ```bash
275 bash scripts/generate-sitemap.sh
276 ```
277
2783. **Performance Testing**
279 - Test with Lighthouse
280 - Verify Core Web Vitals
281 - Check page load times
282 - Validate accessibility scores
283
284## Best Practices
285
286### Routing
287
288- **File Organization**: Group related routes in directories
289- **Index Files**: Use index.astro for directory default pages
290- **Dynamic Parameters**: Name params clearly: [postSlug] not [slug]
291- **404 Handling**: Always provide custom 404.astro page
292- **Redirects**: Use Astro redirects, not client-side navigation
293
294### Component Design
295
296- **Single Responsibility**: Each component does one thing well
297- **Composition**: Use slots and props for flexibility
298- **Type Safety**: Define TypeScript interfaces for all props
299- **Async Loading**: Fetch data in component frontmatter
300- **Minimal Client JS**: Keep components static by default
301
302### Layout Architecture
303
304- **Layout Hierarchy**: Base → Section → Page layouts
305- **Consistent Structure**: All layouts extend base layout
306- **Slot Usage**: Use named slots for flexible content areas
307- **SEO in Base**: Put SEO defaults in base layout
308- **Performance**: Avoid heavy computation in layouts
309
310### Content Management
311
312- **Content Collections**: Use for all structured content
313- **Frontmatter Schema**: Define strict schemas for validation
314- **Type Safety**: Generate TypeScript types from schemas
315- **Markdown**: Use remark/rehype plugins for enhancements
316- **Asset Management**: Store assets in src/ for optimization
317
318### Build Performance
319
320- **Static by Default**: Generate static HTML when possible
321- **Code Splitting**: Split bundles by route
322- **Image Optimization**: Always use Astro Image
323- **Prefetching**: Prefetch critical routes
324- **Caching**: Configure appropriate cache headers
325
326### SEO
327
328- **Semantic HTML**: Use proper heading hierarchy
329- **Meta Tags**: Include title, description, OG tags
330- **Sitemap**: Generate and submit to search engines
331- **Structured Data**: Add JSON-LD for rich results
332- **Performance**: Fast sites rank better
333
334## Common Patterns
335
336### Pattern 1: Dynamic Blog Route
337
338```astro
339---
340// src/pages/blog/[slug].astro
341import { getCollection } from 'astro:content';
342import BlogLayout from '@/layouts/BlogLayout.astro';
343
344export async function getStaticPaths() {
345 const posts = await getCollection('blog');
346 return posts.map(post => ({
347 params: { slug: post.slug }
348 props: { post }
349 }));
350}
351
352const { post } = Astro.props;
353const { Content } = await post.render();
354---
355
356<BlogLayout title={post.data.title} description={post.data.description}>
357 <Content />
358</BlogLayout>
359```
360
361### Pattern 2: Nested Layout Chain
362
363```astro
364---
365// src/layouts/BlogLayout.astro
366import BaseLayout from './BaseLayout.astro';
367
368interface Props {
369 title: string;
370 description: string;
371}
372
373const { title, description } = Astro.props;
374---
375
376<BaseLayout title={title} description={description}>
377 <div class="blog-container">
378 <aside class="sidebar">
379 <!-- Blog sidebar -->
380 </aside>
381 <main class="content">
382 <slot />
383 </main>
384 </div>
385</BaseLayout>
386```
387
388### Pattern 3: Type-Safe Component Props
389
390```astro
391---
392// src/components/Card.astro
393export interface Props {
394 title: string;
395 description?: string;
396 href?: string;
397 variant?: 'default' | 'featured' | 'compact';
398}
399
400const {
401 title
402 description
403 href
404 variant = 'default'
405} = Astro.props;
406---
407
408<div class={`card card-${variant}`}>
409 <h3>{title}</h3>
410 {description && <p>{description}</p>}
411 {href && <a href={href}>Read more</a>}
412</div>
413```
414
415### Pattern 4: API Endpoint
416
417```typescript
418// src/pages/api/posts.ts
419import type { APIRoute } from 'astro';
420import { getCollection } from 'astro:content';
421
422export const GET: APIRoute = async ({ request }) => {
423 const posts = await getCollection('blog');
424
425 return new Response(JSON.stringify(posts), {
426 status: 200
427 headers: {
428 'Content-Type': 'application/json'
429 'Cache-Control': 'public, max-age=3600'
430 }
431 });
432};
433```
434
435### Pattern 5: Optimized Image Usage
436
437```astro
438---
439import { Image } from 'astro:assets';
440import heroImage from '@/assets/hero.jpg';
441---
442
443<Image
444 src={heroImage}
445 alt="Hero image"
446 width={1200}
447 height={600}
448 format="webp"
449 loading="lazy"
450 quality={80}
451/>
452```
453
454## Troubleshooting
455
456### Routes Not Generating
457
458**Problem**: Dynamic routes not building
459
460**Solution**:
4611. Check getStaticPaths returns array of {params, props}
4622. Verify params match route file name: [slug].astro needs params.slug
4633. Ensure all content is available at build time
4644. Check for async issues in getStaticPaths
465
466### Build Performance Issues
467
468**Problem**: Slow build times
469
470**Solution**:
4711. Run: `bash scripts/analyze-performance.sh`
4722. Check for unnecessary data fetching
4733. Optimize images before importing
4744. Review large dependencies
4755. Enable build parallelization
476
477### Component Not Rendering
478
479**Problem**: Component shows blank or errors
480
481**Solution**:
4821. Check component imports use correct path aliases
4832. Verify props interface matches usage
4843. Check for SSR-incompatible code (window, document)
4854. Review error messages in build output
486
487### Layout Not Applied
488
489**Problem**: Layout styles or structure missing
490
491**Solution**:
4921. Verify layout prop is passed correctly
4932. Check layout file exports default component
4943. Ensure base layout includes global styles
4954. Review slot placement in layout chain
496
497### SEO Tags Not Appearing
498
499**Problem**: Meta tags missing from pages
500
501**Solution**:
5021. Check base layout includes SEO component
5032. Verify props passed through layout hierarchy
5043. Inspect generated HTML for meta tags
5054. Ensure head slot is used correctly
506
507## Related Skills
508
509- **component-integration**: For React, MDX, and Tailwind integration
510- **content-collections**: Deep dive into content management
511- **performance-optimization**: Advanced performance tuning
512
513## Requirements
514
515- Node.js 18+
516- Astro 4.0+
517- TypeScript 5.0+
518- Recommended: pnpm or yarn
519
520---
521
522**Plugin**: website-builder
523**Version**: 1.0.0