DEV Community

Hamza Khan
Hamza Khan

Posted on

๐ŸŽจ Mastering Dynamic Routing in Next.js: Build Flexible, Scalable Apps ๐Ÿš€

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! ๐ŸŽ‰๐Ÿ‘จโ€๐Ÿ’ป

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay