src/pages/ directory becomes a page on your site, following the file path.
Basic Routing
Routes are automatically created based on the file structure insrc/pages/:
Astro supports
.astro, .md, .mdx, .html, and .js/.ts files in the pages directory.Static Routes
Create a new file insrc/pages/ to add a static route:
src/pages/about.astro
/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
/blog/first-post, /blog/second-post, etc.
With Props
Pass additional data to each route using theprops 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
/docs/getting-started→path = "getting-started"/docs/guides/installation→path = "guides/installation"/docs/api/reference/config→path = "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
- Supported Methods
- Context Object
Astro supports all standard HTTP methods:
GETPOSTPUTPATCHDELETEOPTIONS
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./posts→posts/index.astro/posts/create→posts/create.astro(static wins over dynamic)/posts/123→posts/[id].astro/posts/a/b/c→posts/[...slug].astro
Route Matching
Astro converts file paths into regular expressions for matching. Fromsrc/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
- Pages (.astro)
- Endpoints (.ts/.js)
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