Bird
Raised Fist0
Astroframework~15 mins

Dynamic routes with parameters in Astro - Deep Dive

Choose your learning style10 modes available
Overview - Dynamic routes with parameters
What is it?
Dynamic routes with parameters in Astro let you create pages that change based on the URL parts. Instead of making a separate page for every possible URL, you use placeholders to catch values like user names or product IDs. This means one page template can show many different things depending on the URL. It helps build websites that feel personal and interactive.
Why it matters
Without dynamic routes, websites would need a separate file for every page, which is slow and hard to manage. Dynamic routes let you handle many pages with one template, saving time and making your site flexible. This is how big websites show different content for each user or product without extra work. It makes websites smarter and easier to grow.
Where it fits
Before learning dynamic routes, you should know basic Astro routing and how to create simple pages. After this, you can learn about fetching data for those routes and using dynamic data in your components. Later, you might explore nested dynamic routes and advanced URL handling.
Mental Model
Core Idea
Dynamic routes use placeholders in URLs to capture parts of the path as parameters, letting one page template serve many different URLs.
Think of it like...
Imagine a mailroom with labeled slots for letters. Instead of making a new slot for every person, you have a slot labeled 'Name' where you put letters for anyone. The slot catches the name on the letter and delivers it to the right person. Dynamic routes work like that slot, catching parts of the URL to show the right content.
┌───────────────┐
│ /users/[id]   │  <-- Dynamic route with [id] as parameter
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Page Template │  <-- Uses 'id' to show user info
└───────────────┘
       │
       ▼
┌───────────────┐
│ URL: /users/42│  <-- '42' captured as id parameter
└───────────────┘
Build-Up - 7 Steps
1
FoundationBasic Astro routing setup
🤔
Concept: Learn how Astro maps files in the pages folder to URLs.
In Astro, any file inside the 'src/pages' folder becomes a webpage. For example, 'src/pages/index.astro' is the homepage at '/'. A file 'about.astro' becomes '/about'. This is called file-based routing.
Result
You get a website where URLs match your file names automatically.
Understanding file-based routing is key because dynamic routes build on this by adding placeholders.
2
FoundationStatic vs dynamic routes difference
🤔
Concept: Static routes have fixed URLs; dynamic routes use placeholders to catch URL parts.
Static route example: 'src/pages/contact.astro' is always '/contact'. Dynamic route example: 'src/pages/blog/[slug].astro' matches '/blog/anything'. The '[slug]' part is a placeholder that changes based on the URL.
Result
You see that dynamic routes let one file handle many URLs by capturing parts of the path.
Knowing this difference helps you decide when to use dynamic routes to avoid making many similar files.
3
IntermediateCreating dynamic route files
🤔Before reading on: do you think you name dynamic route files with curly braces or square brackets? Commit to your answer.
Concept: Astro uses square brackets in filenames to mark dynamic parts of the URL.
To create a dynamic route, name your file with square brackets around the parameter name, like '[id].astro'. This tells Astro to treat that part of the URL as a variable. For example, 'src/pages/products/[id].astro' matches '/products/123' and captures '123' as 'id'.
Result
Astro recognizes URLs matching the pattern and passes the parameter to your page.
Understanding the naming convention is crucial because it controls how Astro matches URLs to your pages.
4
IntermediateAccessing parameters in page components
🤔Before reading on: do you think URL parameters are passed as props or accessed via a special object? Commit to your answer.
Concept: Astro provides URL parameters inside the 'Astro.params' object in your page component.
Inside your dynamic route file, you can get the parameter value from 'Astro.params'. For example, if your file is '[id].astro', you access 'Astro.params.id' to get the value from the URL. You can then use this value to fetch data or display content.
Result
Your page shows content based on the URL parameter, like a product page for the given 'id'.
Knowing how to access parameters lets you make pages that react to the URL dynamically.
5
IntermediateUsing parameters to fetch data
🤔Before reading on: do you think you fetch data before or after rendering the page? Commit to your answer.
Concept: You can use parameters to fetch data during page rendering in Astro's server-side code.
In your dynamic route file, use the parameter from 'Astro.params' to fetch data from an API or database. For example, fetch product details using the 'id' parameter. This happens before the page renders, so the content is ready when the user sees the page.
Result
The page displays data specific to the URL parameter, like product name and price.
Understanding server-side data fetching with parameters enables building personalized and dynamic pages.
6
AdvancedCatch-all routes for flexible URLs
🤔Before reading on: do you think catch-all routes use single or triple dots in filenames? Commit to your answer.
Concept: Catch-all routes use triple dots inside square brackets to capture multiple URL segments.
To match URLs with varying depth, use a catch-all route like '[...slug].astro'. This captures all parts after the base path as an array. For example, '/docs/intro/setup' matches '[...slug].astro' with slug = ['intro', 'setup']. This lets you build flexible nested pages.
Result
Your page can handle URLs with many segments dynamically.
Knowing catch-all routes helps you build complex URL structures without many files.
7
ExpertDynamic routes with optional parameters
🤔Before reading on: do you think Astro supports optional parameters natively or requires workarounds? Commit to your answer.
Concept: Astro supports optional parameters by combining dynamic routes with static routes or using catch-all routes carefully.
Astro does not have built-in syntax for optional parameters like some frameworks. Instead, you create multiple routes: one static and one dynamic, or use catch-all routes and handle missing parameters in code. For example, have 'blog/index.astro' for '/blog' and 'blog/[slug].astro' for '/blog/post'.
Result
You can handle URLs with or without certain parameters gracefully.
Understanding Astro's approach to optional parameters prevents confusion and helps design clean routing.
Under the Hood
Astro's routing system scans the 'src/pages' folder and builds a route map. Files with square brackets become dynamic routes where the bracketed part is a parameter name. When a user visits a URL, Astro matches it against this map, extracts parameter values from the URL path, and passes them to the page component via 'Astro.params'. The page then renders with these values, optionally fetching data server-side before sending HTML to the browser.
Why designed this way?
Astro uses file-based routing with dynamic segments to keep routing simple and intuitive. This design avoids complex configuration files and lets developers see routes directly in the file structure. Using square brackets for parameters is a clear, minimal syntax borrowed from popular frameworks, balancing ease of use with powerful flexibility. Alternatives like manual route definitions were rejected to reduce boilerplate and errors.
src/pages/
├── index.astro          (static route: '/')
├── blog/
│   ├── index.astro      (static route: '/blog')
│   └── [slug].astro     (dynamic route: '/blog/:slug')
└── products/
    └── [...id].astro    (catch-all route: '/products/*')

User visits URL: /blog/hello-world
        │
        ▼
Astro matches '/blog/[slug].astro'
        │
        ▼
Astro.params.slug = 'hello-world'
        │
        ▼
Page renders with slug = 'hello-world'
Myth Busters - 4 Common Misconceptions
Quick: Do you think dynamic route parameters are available as regular JavaScript variables automatically? Commit to yes or no.
Common Belief:Dynamic route parameters become normal variables you can use anywhere without special access.
Tap to reveal reality
Reality:Parameters are only available inside the page component via 'Astro.params' and not as global or regular variables.
Why it matters:Assuming parameters are global leads to errors and undefined values, causing pages to break or show wrong content.
Quick: Do you think you can use parentheses or curly braces instead of square brackets for dynamic routes? Commit to yes or no.
Common Belief:Any bracket style works for dynamic route filenames in Astro.
Tap to reveal reality
Reality:Only square brackets '[param]' are valid for dynamic routes; other brackets are ignored or cause errors.
Why it matters:Using wrong brackets breaks routing and confuses beginners, wasting time debugging.
Quick: Do you think catch-all routes match only one URL segment or multiple? Commit to your answer.
Common Belief:Catch-all routes capture only one part of the URL path.
Tap to reveal reality
Reality:Catch-all routes capture multiple segments as an array, allowing flexible matching of deep URLs.
Why it matters:Misunderstanding this limits your ability to build nested dynamic pages and leads to incorrect route design.
Quick: Do you think optional parameters are natively supported in Astro dynamic routes? Commit to yes or no.
Common Belief:Astro lets you mark parameters as optional directly in the filename.
Tap to reveal reality
Reality:Astro does not support optional parameters in filenames; you must create separate routes or handle missing parameters in code.
Why it matters:Expecting native optional parameters causes confusion and messy routing setups.
Expert Zone
1
Dynamic route parameters are always strings; converting them to numbers or other types must be done manually.
2
Catch-all routes capture parameters as arrays, so you must handle them differently than single string parameters.
3
Astro resolves routes by specificity: static routes take priority over dynamic ones, which affects how you design overlapping routes.
When NOT to use
Avoid dynamic routes when your URLs are fixed and few; static routes are simpler and faster. For very complex routing needs like internationalization or advanced query handling, consider using a dedicated routing library or framework that integrates with Astro.
Production Patterns
In production, dynamic routes are used to build blogs, e-commerce product pages, user profiles, and documentation sites. Developers often combine dynamic routes with server-side data fetching and caching to optimize performance and SEO.
Connections
REST API endpoints
Dynamic routes in Astro resemble REST API path parameters that capture variable parts of URLs.
Understanding dynamic routes helps grasp how REST APIs use URL parameters to identify resources.
Regular expressions
Dynamic route matching is similar to pattern matching in regular expressions, where parts of a string are captured.
Knowing regex groups clarifies how dynamic segments capture URL parts in routing.
Postal addressing system
Like dynamic routes capture parts of a URL, postal addresses break down locations into parts (country, city, street) to deliver mail correctly.
Seeing URLs as addresses helps understand how routing directs users to the right content.
Common Pitfalls
#1Using incorrect brackets for dynamic route files.
Wrong approach:src/pages/[id}.astro
Correct approach:src/pages/[id].astro
Root cause:Confusing bracket types leads to routing errors because Astro only recognizes square brackets for parameters.
#2Trying to access dynamic parameters as normal variables.
Wrong approach:const userId = id; // assuming 'id' is available globally
Correct approach:const userId = Astro.params.id;
Root cause:Misunderstanding how Astro passes parameters causes undefined variable errors.
#3Expecting optional parameters to work in one dynamic route file.
Wrong approach:src/pages/blog/[slug?].astro // assuming '?' makes parameter optional
Correct approach:Create 'src/pages/blog/index.astro' for no slug and 'src/pages/blog/[slug].astro' for slug present.
Root cause:Astro does not support optional parameters in filenames, so this syntax is invalid.
Key Takeaways
Dynamic routes in Astro use square brackets in filenames to capture URL parts as parameters.
Parameters are accessed inside page components via the 'Astro.params' object, not as regular variables.
Catch-all routes with triple dots capture multiple URL segments as arrays for flexible routing.
Astro does not support optional parameters in filenames; handle them with separate routes or code logic.
Understanding dynamic routes lets you build scalable, flexible websites that serve many pages from few templates.

Practice

(1/5)
1. What does a filename like [id].astro represent in Astro?
easy
A. A dynamic route that captures the id parameter from the URL
B. A static page named literally [id]
C. A component that cannot receive parameters
D. A special Astro configuration file

Solution

  1. Step 1: Understand dynamic route syntax

    In Astro, square brackets in filenames like [id].astro define a dynamic route parameter named id.
  2. Step 2: Recognize the purpose of the parameter

    This parameter captures part of the URL, allowing the page to change based on the URL segment.
  3. Final Answer:

    A dynamic route that captures the id parameter from the URL -> Option A
  4. Quick Check:

    Dynamic route = filename with [param] [OK]
Hint: Look for square brackets in filename for dynamic parameters [OK]
Common Mistakes:
  • Thinking [id].astro is a static file
  • Confusing parameter with component name
  • Assuming parameters are optional by default
2. Which is the correct way to access a dynamic route parameter named slug inside an Astro component?
easy
A. Astro.query.slug
B. Astro.route.slug
C. Astro.params.slug
D. Astro.props.slug

Solution

  1. Step 1: Recall Astro parameter access

    Astro provides dynamic route parameters inside the component via Astro.params.
  2. Step 2: Use the parameter name as key

    To get the value of slug, use Astro.params.slug.
  3. Final Answer:

    Astro.params.slug -> Option C
  4. Quick Check:

    Access params with Astro.params.[name] [OK]
Hint: Use Astro.params to get dynamic route values [OK]
Common Mistakes:
  • Using Astro.route or Astro.query instead of Astro.params
  • Trying to access parameters via props
  • Forgetting to use the exact parameter name
3. Given a file named src/pages/blog/[post].astro with this code snippet:
---
const postId = Astro.params.post;
---

Post ID: {postId}


What will be rendered when visiting /blog/42?
medium
A.

Post ID: 42

B.

Post ID: post

C.

Post ID:

D. 404 Not Found

Solution

  1. Step 1: Identify dynamic parameter value

    The URL /blog/42 matches the dynamic route [post].astro, so Astro.params.post is '42'.
  2. Step 2: Render the parameter in the template

    The component outputs <h1>Post ID: {postId}</h1>, so it shows Post ID: 42.
  3. Final Answer:

    <h1>Post ID: 42</h1> -> Option A
  4. Quick Check:

    URL segment fills param = rendered value [OK]
Hint: URL segment replaces [param] and shows in Astro.params [OK]
Common Mistakes:
  • Expecting literal 'post' instead of parameter value
  • Assuming empty or missing parameter
  • Confusing 404 with dynamic route handling
4. You have a dynamic route file named [user].astro but when visiting /john you get a runtime error: Cannot read property 'user' of undefined. What is the likely cause?
medium
A. Astro.params is only available in server components
B. You forgot to use Astro.params.user and accessed Astro.params directly
C. Dynamic routes cannot have parameters named 'user'
D. The filename should be {user}.astro instead of [user].astro

Solution

  1. Step 1: Understand the error message

    The error says Cannot read property 'user' of undefined, meaning Astro.params is undefined or not accessed properly.
  2. Step 2: Check parameter access syntax

    Accessing Astro.params.user is correct. If code tries to access Astro.params.user but Astro.params is undefined, it means Astro.params was not used or imported correctly.
  3. Final Answer:

    You forgot to use Astro.params.user and accessed Astro.params directly -> Option B
  4. Quick Check:

    Always use Astro.params.[param] to avoid undefined errors [OK]
Hint: Always access parameters via Astro.params.[name] [OK]
Common Mistakes:
  • Using curly braces instead of square brackets in filename
  • Assuming Astro.params is always defined globally
  • Misnaming the parameter in code
5. You want to create a nested dynamic route in Astro to handle URLs like /products/electronics/123. Which file structure and parameter access is correct?
hard
A. Create src/pages/products/[category]/id.astro and access with Astro.params.id
B. Create src/pages/products/[category-id].astro and access with Astro.params['category-id']
C. Create src/pages/products/category/id.astro and access with Astro.params.category and Astro.params.id
D. Create src/pages/products/[category]/[id].astro and access with Astro.params.category and Astro.params.id

Solution

  1. Step 1: Understand nested dynamic routes

    To match URLs like /products/electronics/123, you need nested folders with dynamic parameters: [category] and [id].
  2. Step 2: Correct file structure and parameter access

    The correct structure is src/pages/products/[category]/[id].astro. Inside, access parameters as Astro.params.category and Astro.params.id.
  3. Final Answer:

    Create src/pages/products/[category]/[id].astro and access with Astro.params.category and Astro.params.id -> Option D
  4. Quick Check:

    Nested folders with [param] = nested params [OK]
Hint: Use nested folders with [param] for multi-level dynamic routes [OK]
Common Mistakes:
  • Combining multiple params in one filename incorrectly
  • Using static folder names instead of dynamic
  • Accessing parameters that don't exist in the route
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard