Pages and routing
Declare a dynamic route
Capture a URL segment with square brackets when one template renders several related pages.
8 minute lesson
A dynamic segment lets one page template represent several URLs.
src/pages/posts/[slug].astro
The bracket name becomes a route parameter. A request for /posts/hello-astro/ has a slug value of hello-astro.
Inside the page:
---
const { slug } = Astro.params
---
<h1>Post: {slug}</h1>
The parameter tells you which route matched. It is still input. Validate it before using it in a database query, file path, or authorization decision.
Rendering mode changes how the value becomes available. A static project needs the complete set of slugs during the build, provided by getStaticPaths(). An on-demand route can receive the current request parameter at runtime but needs a compatible adapter.
Use [...slug].astro for a rest parameter that can match several path segments. Choose it only when nested paths are part of the content model.
Create one dynamic route and try a known and unknown value. Decide whether the unknown path should be built, return a 404, or be handled on demand.
Lesson completed