Using Slugs in Next.js for Dynamic Routing

Introduction

Slugs are user-friendly, URL-safe strings used to identify resources. In Next.js, slugs are commonly used for dynamic routes, such as blog posts, products, or user profiles. This article covers how to implement and use slugs in Next.js.

1. Setting Up a Dynamic Route

To create a dynamic route using slugs, create a file inside the pages directory with square brackets ([slug].js or [slug].tsx).

/pages

 /blog

  [slug].js

Inside [slug].js, use getStaticProps and getStaticPaths to fetch data at build time.

2. Fetching Data Using getStaticProps and getStaticPaths

Example: Fetching a Blog Post

import { useRouter } from ‘next/router’;

export async function getStaticPaths() {

 // Fetch available slugs from an API or database

 const res = await fetch(‘https://api.example.com/posts’);

 const posts = await res.json();

 const paths = posts.map((post) => ({

  params: { slug: post.slug },

 }));

 return { paths, fallback: false };

}

export async function getStaticProps({ params }) {

 // Fetch post details based on slug

 const res = await fetch(`https://api.example.com/posts/${params.slug}`);

 const post = await res.json();

 return {

  props: { post },

 };

}

export default function BlogPost({ post }) {

 const router = useRouter();

 // Show a loading state if the page is not yet generated

 if (router.isFallback) {

  return <div>Loading…</div>;

 }

 return (

  <div>

   <h1>{post.title}</h1>

   <p>{post.content}</p>

  </div>

 );

}

3. Explanation

  • getStaticPaths: Generates paths for each blog post at build time.
  • getStaticProps: Fetches data for the requested slug.
  • router.isFallback: Handles loading state for pages not pre-generated.

4. Handling Fallback Pages

Set fallback: true or fallback: 'blocking' in getStaticPaths to dynamically generate new pages at runtime.

return { paths, fallback: ‘blocking’ };

5. Client-Side Navigation with next/link

To link to slug-based pages, use next/link:

import Link from ‘next/link’;

export default function BlogList({ posts }) {

 return (

  <ul>

   {posts.map((post) => (

    <li key={post.id}>

     <Link href={`/blog/${post.slug}`}>

      {post.title}

     </Link>

    </li>

   ))}

  </ul>

 );

}

Leave a comment

Your email address will not be published. Required fields are marked *