#Dynamic but limited route path

3 messages · Page 1 of 1 (latest)

graceful sapphire
#

Let's supose in an e-commerce we have brands/women, brands/men, brands/kids.

We can create a folder brands and then 3 individual astro files: women.astro, men.astro and kids.astro. But will end up repeating some code. Is there a better way, like creating a [women|men|kids].astro file or similar?

coral wyvernBOT
#

Hi @graceful sapphire. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Astro’s routing doesn’t support “union” parameters like [women|men|kids].astro. Dynamic segments are always a single param name like [category].astro or a rest param like [...slug].astro. [Routing guide]

For your case, the usual pattern is:

src/pages/brands/[category].astro:

---
const { category } = Astro.params; // "women", "men", "kids", etc.

// Optionally, restrict to allowed values:
const allowed = ["women", "men", "kids"];
if (!allowed.includes(category)) {
  return Astro.redirect("/404"); // or Astro.rewrite("/404") in newer Astro
}
---

<h1>Brands for {category}</h1>
<!-- shared layout / logic here -->

This way you:

  • Have a single file (no duplicated code).
  • Still get separate URLs: /brands/women, /brands/men, /brands/kids. [Routing guide]

If you’re in static (SSG) mode and want only those three pages generated, add getStaticPaths():

---
export function getStaticPaths() {
  return [
    { params: { category: "women" } },
    { params: { category: "men" } },
    { params: { category: "kids" } },
  ];
}

const { category } = Astro.params;
---
<h1>Brands for {category}</h1>

This is the recommended way to have “dynamic but limited” routes in Astro. [getStaticPaths]

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: