codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
▲

Next.js

6 / 73 topics
4File System Routing5Pages Directory6Dynamic Routes7Catch All Routes
Tutorials/Next.js/Dynamic Routes
▲Next.js

Dynamic Routes

Updated 2026-04-20
2 min read

Dynamic Routes

Dynamic routes are a powerful feature of Next.js that allow you to create pages with URLs that include parameters, making your application more flexible and dynamic. This section will cover how to set up dynamic routes, how they work under the hood, and best practices for using them in your Next.js applications.

Introduction to Dynamic Routes

Dynamic routes enable you to build pages that can respond to different data inputs. For example, instead of creating a separate page for each blog post, you can use a single dynamic route to handle all posts based on their unique identifiers (e.g., /posts/[id]). This approach is not only more efficient but also easier to maintain.

Setting Up Dynamic Routes

Basic Structure

To create a dynamic route in Next.js using the App Router, you need to define a file with square brackets ([]) around the parameter name inside the app directory. For instance, to create a dynamic route for blog posts by ID, you would create a file named app/posts/[id]/page.js.

// app/posts/[id]/page.js

export default async function Post({ params }) {
  const { id } = params;
  const res = await fetch(`https://api.example.com/posts/${id}`);
  const post = await res.json();

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

Fetching Data

You can fetch data for a dynamic route using async functions within your page component.

// app/posts/[id]/page.js

export default async function Post({ params }) {
  const { id } = params;
  const res = await fetch(`https://api.example.com/posts/${id}`);
  const post = await res.json();

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

Fallback Routes

When using the App Router, you can handle fallbacks by checking if data is available.

// app/posts/[id]/page.js

export default async function Post({ params }) {
  const { id } = params;
  try {
    const res = await fetch(`https://api.example.com/posts/${id}`);
    const post = await res.json();

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

Best Practices

Use Dynamic Routes Sparingly

Dynamic routes can add complexity to your application. Only use them when necessary, such as for blog posts or product pages where the number of unique URLs is large and unpredictable.

Optimize Data Fetching

Ensure that data fetching is optimized to avoid unnecessary requests. Use caching strategies like revalidate in getStaticProps to control how often data is refreshed.

// Example with revalidation
export async function generateMetadata({ params }) {
  const { id } = params;
  const res = await fetch(`https://api.example.com/posts/${id}`);
  const post = await res.json();

  return {
    title: post.title,
  };
}

export default async function Post({ params }) {
  const { id } = params;
  const res = await fetch(`https://api.example.com/posts/${id}`, {
    next: { revalidate: 10 }, // Revalidate every 10 seconds
  });
  const post = await res.json();

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

Handle Errors Gracefully

Implement error handling to manage cases where data fetching fails or returns unexpected results. Use try-catch blocks and provide fallback content.

export default async function Post({ params }) {
  const { id } = params;
  try {
    const res = await fetch(`https://api.example.com/posts/${id}`);
    const post = await res.json();

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

Use Link Component for Navigation

When navigating between dynamic routes, use the Link component from Next.js to optimize performance and ensure smooth transitions.

import Link from 'next/link';

function PostList({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          <Link href={`/posts/${post.id}`}>
            <a>{post.title}</a>
          </Link>
        </li>
      ))}
    </ul>
  );
}

Conclusion

Dynamic routes in Next.js provide a powerful way to create flexible and dynamic pages. By understanding how they work and following best practices, you can build efficient and maintainable applications that respond well to user input and data changes. Whether you're building a blog, an e-commerce site, or any other type of application, dynamic routes are an essential tool in your Next.js developer toolkit.


PreviousPages DirectoryNext Catch All Routes

Recommended Gear

Pages DirectoryCatch All Routes