🎨 Mastering Dynamic Routing in Next.js: Build Flexible, Scalable Apps 🚀

Hamza Khan - Sep 16 - - Dev Community

Next.js is a powerhouse framework that makes creating React apps easier and more efficient. One of its most powerful features is dynamic routing, allowing you to build flexible, scalable web applications with cleaner URLs and better user experiences.

Let’s get into it! ⚡️

🛣️ What is Dynamic Routing?

In Next.js, dynamic routing means creating pages based on dynamic content like blog posts, user profiles, or products. Instead of hardcoding each page, you can create routes that generate pages on the fly based on dynamic parameters.

For example:

  • /posts/1
  • /posts/2
  • /users/johndoe
  • /users/janedoe

All of these URLs can be handled by a single dynamic route in Next.js.

🔧 Setting Up Dynamic Routes

Let’s start with an example where we want to create a blog app with dynamic URLs for each blog post.

1️⃣ Create a Dynamic Route

In Next.js, to create a dynamic route, you simply need to add square brackets [ ] to the page’s file name in the pages directory.

/pages/posts/[id].js
Enter fullscreen mode Exit fullscreen mode

This file will dynamically handle any URL pattern like /posts/1 or /posts/abc.

2️⃣ Fetch Dynamic Data in the Page

Now, let’s fetch data for the specific post using the getStaticProps and getStaticPaths functions.

// pages/posts/[id].js
import { useRouter } from 'next/router';

export default function Post({ post }) {
  const router = useRouter();

  // If the page is still loading or not yet generated
  if (router.isFallback) {
    return <div>Loading...</div>;
  }

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

// Fetch the paths for dynamic routes
export async function getStaticPaths() {
  const res = await fetch('https://myapi.com/posts');
  const posts = await res.json();

  const paths = posts.map(post => ({
    params: { id: post.id.toString() },
  }));

  return { paths, fallback: true };
}

// Fetch data for each post based on the ID
export async function getStaticProps({ params }) {
  const res = await fetch(`https://myapi.com/posts/${params.id}`);
  const post = await res.json();

  return {
    props: {
      post,
    },
    revalidate: 10, // Optional: Rebuild page every 10 seconds
  };
}
Enter fullscreen mode Exit fullscreen mode

What’s Happening Here?

  • getStaticPaths: Tells Next.js which dynamic routes to pre-render. It fetches a list of post IDs from the API and dynamically generates the paths.
  • getStaticProps: For each route, it fetches the necessary data based on the ID from the URL and passes it to the component as props.

This setup allows us to generate static pages for each blog post, improving performance and SEO.

⚡️ Dynamic Routing with Catch-All Routes

Sometimes, you need to handle more complex routing patterns, like /category/sports/post/123. In this case, Next.js supports catch-all routes, which can handle multiple dynamic segments.

To create a catch-all route, add [...params].js:

/pages/posts/[...params].js
Enter fullscreen mode Exit fullscreen mode

Now, any URL like /posts/category/sports/post/123 will be handled by this file.

Fetch Data for Catch-All Routes

// pages/posts/[...params].js
import { useRouter } from 'next/router';

export default function Post({ post }) {
  const router = useRouter();
  const { params } = router.query;

  if (router.isFallback) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Post from {params.join('/')}</h1>
      <p>{post.content}</p>
    </div>
  );
}

export async function getStaticPaths() {
  return {
    paths: [],
    fallback: true,
  };
}

export async function getStaticProps({ params }) {
  const slug = params.join('/');
  const res = await fetch(`https://myapi.com/posts/${slug}`);
  const post = await res.json();

  return {
    props: { post },
  };
}
Enter fullscreen mode Exit fullscreen mode

With this, you can handle URLs like /posts/category/sports/post/123 and treat each dynamic part of the path accordingly.

🌟 Benefits of Dynamic Routing in Next.js

  • Scalability: You don’t need to create separate pages for each blog post or user profile. The routing is dynamic and handles large volumes of content easily.
  • Cleaner URLs: Dynamic routes allow you to create user-friendly and SEO-optimized URLs.
  • Performance: By combining dynamic routing with SSG (Static Site Generation) or ISR (Incremental Static Regeneration), your app stays fast and responsive.

👨‍💻 Final Thoughts

Dynamic routing is a powerful feature in Next.js that allows you to build highly flexible applications. Whether you're building a blog, an e-commerce site, or a large app with multiple content types, dynamic routing lets you create scalable, maintainable URLs with ease.

Start using dynamic routes in your Next.js app and take your web development skills to the next level! 💪


Further Reading:


Happy coding! 🎉👨‍💻

. . . . . . . . . . . . . . . . . . . . .
Terabox Video Player