Astro Routing Mastery
Explore Astro's powerful file-based routing system with static routes, dynamic parameters, pagination, redirects, and advanced patterns.
SSG vs SSR Decision Framework
Use SSG When
- Content rarely changes (marketing pages, docs)
- SEO-critical pages needing fast loading
- Known routes at build time
- Public content without user-specific data
Use SSR When
- User-specific content (dashboards, profiles)
- Real-time data that changes frequently
- Pages depending on request headers/cookies
- Dynamic content from user input/database
Interactive Routing Examples
Static vs Dynamic Routes
Understanding when to use SSG vs SSR
Multi-Level Dynamic Routing
Complex nested route structures
Pagination Examples
Paginated content with dynamic routes
Route Priority Demos
Understanding how Astro resolves conflicting routes
Advanced Patterns
Redirects, rewrites, and middleware examples
Code Examples
SSG Route (Prerendered)
---
// src/pages/static-example.astro
export const prerender = true; // Force SSG
const staticData = {
title: "Fast Loading Page",
loadTime: "< 50ms",
seo: "Excellent"
};
---
<h1>{staticData.title}</h1>
<p>This page is pre-rendered at build time</p> SSR Route (Dynamic)
---
// src/pages/dynamic-example.astro
// No prerender = SSR by default
const userAgent = Astro.request.headers.get('user-agent');
const currentTime = new Date().toLocaleString();
---
<h1>Dynamic Content</h1>
<p>Generated at: {currentTime}</p>
<p>Your browser: {userAgent}</p> Multi-Level Dynamic Route
---
// src/pages/pets/[species]/[name]/care/[...activity].astro
export const prerender = false;
const { species, name, activity } = Astro.params;
const activityPath = activity || '';
// Mock pet data
const petData = {
species,
name,
currentActivity: activityPath.split('/').pop() || 'resting'
};
---
<h1>{petData.name} the {petData.species}</h1>
<p>Activity: {petData.currentActivity}</p> Paginated Route
---
// src/pages/events/[city]/[page].astro
export function getStaticPaths() {
const cities = ['san-francisco', 'new-york', 'london'];
const pages = [1, 2, 3];
return cities.flatMap(city =>
pages.map(page => ({
params: { city, page: page.toString() }
}))
);
}
const { city, page } = Astro.params;
const events = getEventsForCity(city, parseInt(page));
--- Route Priority Order
When multiple routes could match the same URL, Astro uses this priority order:
Static routes without path parameters
/blog/create.astro
Dynamic routes with named parameters
/blog/[slug].astro
Dynamic routes with rest parameters
/blog/[...path].astro
File-based routes vs redirects
Physical files take precedence
Performance & Best Practices
SSG Performance
Pre-rendered pages load in <50ms with perfect SEO
Smart Caching
Cache static assets, personalize dynamic content
Progressive Enhancement
Start static, add interactivity where needed