recent posts

Dynamic Routing in Next.js: Handling Dynamic Parameters

Dynamic Routing in Next.js: Handling Dynamic Parameters

Dynamic routing is a powerful feature in Next.js that allows you to handle routes with dynamic parameters, such as /blog/[slug] or /users/[id]. This is particularly useful for building applications with dynamic content, such as blogs, e-commerce platforms, or user profiles. In this article, we’ll explore how dynamic routing works in Next.js and how you can use it to create flexible and scalable applications.

How Dynamic Routing Works

In Next.js, dynamic routes are created by adding square brackets to the file name in the pages directory. For example, a file named [slug].js in the pages/blog directory will handle routes like /blog/first-post and /blog/second-post, where slug is a dynamic parameter.

Creating a Dynamic Route

To create a dynamic route, follow these steps:

  1. Create a new file in the pages directory with square brackets in the file name. For example, pages/blog/[slug].js.
  2. Use the useRouter hook from Next.js to access the dynamic parameter in your component.

// pages/blog/[slug].js
import { useRouter } from 'next/router';

export default function BlogPost() {
  const router = useRouter();
  const { slug } = router.query;

  return (
    <div>
      <h1>Blog Post: {slug}</h1>
      <p>This is the content for the blog post titled "{slug}".</p>
    </div>
  );
}

In this example, the slug parameter is extracted from the URL and used to display the blog post title and content.

Fetching Data for Dynamic Routes

Dynamic routes often require fetching data based on the dynamic parameter. Next.js provides two functions for fetching data in dynamic routes: getStaticProps and getServerSideProps.

Using getStaticProps

getStaticProps is used for static site generation (SSG). It fetches data at build time and generates static HTML files for each dynamic route.


// pages/blog/[slug].js
export async function getStaticProps({ params }) {
  const res = await fetch(`https://api.example.com/posts/${params.slug}`);
  const post = await res.json();

  return {
    props: {
      post,
    },
  };
}

export default function BlogPost({ post }) {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
}

Using getServerSideProps

getServerSideProps is used for server-side rendering (SSR). It fetches data on each request, ensuring that the data is always up-to-date.


// pages/blog/[slug].js
export async function getServerSideProps({ params }) {
  const res = await fetch(`https://api.example.com/posts/${params.slug}`);
  const post = await res.json();

  return {
    props: {
      post,
    },
  };
}

export default function BlogPost({ post }) {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
}

Handling Multiple Dynamic Segments

Next.js also supports routes with multiple dynamic segments. For example, you can create a route like /category/[categoryId]/product/[productId] by adding a file named [categoryId]/[productId].js in the pages/category directory.


// pages/category/[categoryId]/product/[productId].js
import { useRouter } from 'next/router';

export default function Product() {
  const router = useRouter();
  const { categoryId, productId } = router.query;

  return (
    <div>
      <h1>Category: {categoryId}</h1>
      <h2>Product: {productId}</h2>
    </div>
  );
}

Secrets and Hidden Facts

  • Catch-All Routes: Use [...slug].js to create catch-all routes that match multiple segments.
  • Optional Catch-All Routes: Use [[...slug]].js to create optional catch-all routes.
  • Fallback Pages: Use the fallback option in getStaticPaths to generate pages on-demand.

Conclusion

Dynamic routing is a powerful feature in Next.js that allows you to handle routes with dynamic parameters, making it ideal for building applications with dynamic content. Whether you’re fetching data for blog posts, user profiles, or e-commerce products, Next.js provides the tools and flexibility you need to create scalable and maintainable applications.

Dynamic Routing in Next.js: Handling Dynamic Parameters Dynamic Routing in Next.js: Handling Dynamic Parameters Reviewed by Curious Explorer on Tuesday, February 25, 2025 Rating: 5

No comments:

Powered by Blogger.