Skip to main content
Astro uses file-based routing to generate your site’s URLs. Every file in your src/pages/ directory becomes a page on your site, following the file path.

Basic Routing

Routes are automatically created based on the file structure in src/pages/:
Astro supports .astro, .md, .mdx, .html, and .js/.ts files in the pages directory.

Static Routes

Create a new file in src/pages/ to add a static route:
src/pages/about.astro
This creates a page accessible at /about.

Dynamic Routes

Dynamic routes use bracket notation [param] in filenames to match any value at that position in the URL path.

Single Parameter

src/pages/blog/[slug].astro
This matches /blog/first-post, /blog/second-post, etc.

With Props

Pass additional data to each route using the props object:
src/pages/blog/[id].astro

Multiple Parameters

Use multiple dynamic segments:
src/pages/[category]/[item].astro

Rest Parameters

Use [...path] for catch-all routes:
src/pages/docs/[...path].astro
This matches:
  • /docs/getting-startedpath = "getting-started"
  • /docs/guides/installationpath = "guides/installation"
  • /docs/api/reference/configpath = "api/reference/config"
Rest parameters can match paths at any depth, making them perfect for documentation or file browsers.

API Routes

Create API endpoints by exporting HTTP method handlers from .js or .ts files:
src/pages/api/posts.json.ts
Astro supports all standard HTTP methods:
  • GET
  • POST
  • PUT
  • PATCH
  • DELETE
  • OPTIONS

Route Priority

When multiple routes could match a URL, Astro uses a priority system to determine which route to use. From the source code (src/core/routing/priority.ts), routes are prioritized as follows:
1

Static routes

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

Dynamic routes

Routes with parameters like /blog/[slug].astro come next.
3

Rest parameters

Catch-all routes like /[...path].astro have lowest priority.
Given these files:
Requests resolve as:
  • /postsposts/index.astro
  • /posts/createposts/create.astro (static wins over dynamic)
  • /posts/123posts/[id].astro
  • /posts/a/b/cposts/[...slug].astro

Route Matching

Astro converts file paths into regular expressions for matching. From src/core/routing/pattern.ts:
How it works: File paths are broken into segments, converted to regex patterns, then matched against incoming URLs.

Page vs. Endpoint

Return HTML content:

Practical Examples

Blog with Pagination

src/pages/blog/[page].astro

Dynamic API with Database

src/pages/api/users/[id].ts

Best Practices

Use Static Routes When Possible

They’re faster and easier to understand.

Organize with Folders

Group related pages together for better maintainability.

Type Your API Routes

Use TypeScript for better type safety in endpoints.

Handle Errors

Always return appropriate status codes in API routes.

Learn More

Layouts

Reuse common page structures

Content Collections

Type-safe content with built-in routing