Skip to content

Dynamic Routing in Astro

To render new stories dynamically, set up a catch-all route in the Astro project.

Create a src/pages/[...slug].astro file to fetch all stories in the space.

src/pages/[...slug].astro
---
import { getPayload, StoryblokPreview } from "@storyblok/astro";
import { apiClient, StoryblokBlock } from "../storyblok";
import Layout from "../layouts/Layout.astro";
const { slug } = Astro.params;
const payload = await getPayload({ locals: Astro.locals });
const story =
payload.story ??
(
await apiClient.stories.get(slug || "home", {
query: {
version: "draft",
},
})
).data?.story;
if (!story) {
return new Response(null, { status: 404 });
}
---
<Layout>
<StoryblokBlock block={story.content} />
<StoryblokPreview liveUpdate />
</Layout>

Get the slug from the current route parameters, making an exception for the home story to be /. If no story matches the slug, the page returns a 404 response.

With this approach, your project can automatically handle new stories you add to your space.

Was this page helpful?

What went wrong?

This site uses reCAPTCHA and Google's Privacy Policy (opens in a new window).Terms of Service (opens in a new window) apply.