Skip to main content

Overview

Astro uses file-based routing, where files in src/pages/ automatically become routes on your site. This guide covers common routing patterns and advanced techniques.

File-Based Routing

The structure of your src/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:
1

Static routes

Exact file matches like /about.astro have highest priority.
2

Dynamic routes

Single parameter routes like /[id].astro are checked next.
3

Catch-all routes

Catch-all routes like /[...path].astro have lowest priority.

Example Routing Order

Advanced Patterns

Create paginated routes for large datasets:
src/pages/blog/[page].astro
Structure routes for multiple languages:
Or use dynamic routing:
src/pages/[lang]/[...slug].astro
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

1

Route conflicts

If routes conflict, check the priority order. More specific routes should be in separate files.
2

Dynamic routes not generating

Ensure getStaticPaths() is exported and returns the correct format.
3

Redirects not working

Verify your adapter supports redirects. Some static hosts require additional configuration.