Overview
Astro uses file-based routing, where files insrc/pages/ automatically become routes on your site. This guide covers common routing patterns and advanced techniques.
File-Based Routing
The structure of yoursrc/pages/ directory determines your site’s URL structure.
Basic Routes
Nested Routes
Create nested directories for organized URL structures:Dynamic Routes
Use square brackets[param] to create dynamic route parameters.
Single Parameter
src/pages/products/[id].astro
Static Path Generation
For static sites, generate all possible paths at build time:src/pages/products/[id].astro
Multiple Parameters
src/pages/blog/[year]/[month]/[slug].astro
Catch-All Routes
Use[...path] to match any number of path segments.
Basic Catch-All
src/pages/[...path].astro
Documentation Site Pattern
src/pages/docs/[...slug].astro
Named Catch-All with Fallback
src/pages/blog/[...slug].astro
Redirects
Handle redirects for moved content, aliases, and legacy URLs.Static Redirects
Define redirects in your Astro config:astro.config.mjs
Dynamic Redirects
Handle redirects programmatically:src/pages/legacy/[id].astro
Conditional Redirects
src/pages/dashboard.astro
API Routes
Create API endpoints that return JSON or other data formats.Basic API Route
src/pages/api/products.ts
Dynamic API Routes
src/pages/api/products/[id].ts
POST Requests
src/pages/api/contact.ts
Priority and Route Matching
Astro resolves routes with this priority order:Example Routing Order
Advanced Patterns
Pagination
Pagination
Create paginated routes for large datasets:
src/pages/blog/[page].astro
Internationalization (i18n)
Internationalization (i18n)
Structure routes for multiple languages:Or use dynamic routing:
src/pages/[lang]/[...slug].astro
Custom 404 Pages
Custom 404 Pages
Create a custom 404 page:
src/pages/404.astro
Best Practices
Organize by Feature
Group related pages in directories for better maintainability.
Use Named Parameters
Choose descriptive parameter names like
[slug] or [id] instead of generic names.Handle Edge Cases
Always validate parameters and handle missing data gracefully.
Leverage TypeScript
Use TypeScript for type-safe routing and API routes.
Troubleshooting
Route conflicts
If routes conflict, check the priority order. More specific routes should be in separate files.