Ever wondered how to make your Next.js blog dynamic and static at the same time? 🤔 You're in luck! This friendly guide will walk you through implementing dynamic routes in Next.js using the magical [slug]
parameters.
A route path is basically the URL structure for your route. Think of it as the address to your favorite ice cream shop. 🍦 It can include parameters (placeholders for dynamic values) that let you switch up the content. Super cool, right?
The route handler is what makes the magic happen when someone visits your route. In the magical world of the Next.js app router, this can be found in layout.tsx
, page.tsx
, or route.tsx
. But for our adventure, we're zooming into page.tsx
.
Let's dive into some code to make your blog dynamic! 🏊♀️
Here's a peek at what you’ll place in src/app/article/[slug]/page.tsx
:
const generateStaticParams = async () => { const slugs = await getArticleSlugs(); return slugs.map(async ({ slug }) => ({ params: { slug, }, })); }; const ArticlePage = async (props: ArticleProps) => { const { frontMatter, content } = await getArticleBySlug( props.params.slug ); //... return ( <div> ... </div> ); };
generateStaticParams
?Great question! For our markdown-driven, static blog, we need to access the file system. However, doing so outside of the build phase is a no-go. 🚫 Therefore, generating routes at build time is a must. This ensures that all possible valid paths are pre-generated, making the blog fast and efficient.⚡
In simpler terms, you need to generate a list of slugs at build time. Next.js will take these and create all the pages for your site, ready to be served to your visitors. 🏗️ Build once, serve forever!
Want to learn more about dynamic routes and slugs? Check out these awesome resources:
Happy Coding! ✨
We use cookies to improve your experience and analyze our traffic. By using our site, you consent to our use of cookies. You can manage your preferences below: