Dynamic Routing in Next.js
Set up a catch-all route in the Next.js project to render new stories dynamically.
Fetch and render a story dynamically
Create a new file src/app/[...slug]/page.js
file to fetch all stories in the space.
import { StoryblokStory } from '@storyblok/react/rsc';
import { getStoryblokApi } from '@/lib/storyblok';
export default async function Page({ params }) {
const { slug } = await params;
let fullSlug = slug ? slug.join('/') : 'home';
let sbParams = {
version: 'draft',
};
const storyblokApi = getStoryblokApi();
let { data } = await storyblokApi.get(`cdn/stories/${fullSlug}`, sbParams);
return <StoryblokStory story={data.story} />;
}
Get the slug
from the current route parameters, making an exception for the home story to be /
.
Remove the src/app/page.js
file from the project, as it’s no longer needed.
With this setup, dynamic stories are always rendered on the server for each request. Use the links endpoint of the Content Delivery API and generateStaticParams()
to provide all routes. Learn more about static rendering in Next.js documentation.
Next Part
Content Modeling in Next.jsPrevious Part
Visual Preview in Next.js