Nextjs [slug] dynamic routes

Learn how to implement dynamic routes in Next.js using [slug] parameters. This guide covers route paths, handlers, and generating static parameters for a static markdown blog.

How to Implement Dynamic Routes in Next.js Using [Slug] Parameters

Learn to create dynamic routes in Next.js! 🚀

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.

What's Inside?

  1. Route Paths
  2. Route Handlers
  3. Generating Static Parameters

Step 1: Understanding Route Paths

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?

Step 2: Grasping Route Handlers

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.

Step 3: Code Example – Creating Articles with [Slug]

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>
  );
};

Why Do We Need 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!

More Resources

Want to learn more about dynamic routes and slugs? Check out these awesome resources:

Happy Coding! ✨

← Back to posts

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: