Dynamic Routing in Astro
To render new stories dynamically, set up a catch-all route in the Astro project.
Fetch and render a story dynamically
Section titled “Fetch and render a story dynamically”Create a src/pages/[...slug].astro file to fetch all stories in the space.
---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.
Related resources
Section titled “Related resources”Was this page helpful?
This site uses reCAPTCHA and Google's Privacy Policy (opens in a new window).Terms of Service (opens in a new window) apply.
- Need help?Contact support (opens in a new window)
- Something isn’t right?Check system status (opens in a new window)
Get in touch with the Storyblok community