homeblog

Building Dynamic Routes in Next.js: A Complete Guide

Mon Dec 02 2024
Building Dynamic Routes in Next.js: A Complete Guide

Aymen Jdily

Building Dynamic Routes in Next.js: A Complete Guide

Building Dynamic Routes in Next.js: A Complete Guide

Introduction

Routing forms the backbone of any web application, enabling users to navigate seamlessly between pages. With Next.js, routing is straightforward, thanks to its file-based routing system. But when building dynamic apps like blogs, e-commerce sites, or dashboards, dynamic routes become essential. This guide walks you through the basics and advanced techniques of dynamic routing in Next.js.

1. What Are Dynamic Routes?

Dynamic routes let you create pages based on dynamic data such as user IDs, product slugs, or any variable. Instead of hardcoding routes like /blog/post-1, you can define a dynamic route, /blog/[slug], that adapts to any slug passed in the URL.

2. Creating a Dynamic Route

Step 1: Set Up the Folder and File

  • Inside your pages directory, create a folder blog.
  • Add a file named [slug].js to handle routes like /blog/my-first-post.

Step 2: Add Dynamic Routing Logic

In pages/blog/[slug].js, use the useRouter hook to access the route parameter:

1import { useRouter } from 'next/router';
2
3const BlogPost = () => {
4  const router = useRouter();
5  const { slug } = router.query;
6
7  return <h1>Blog Post: {slug}</h1>;
8};
9
10export default BlogPost;

Step 3: Test the Route

Run your development server (npm run dev) and visit /blog/my-first-post. You should see:
Blog Post: my-first-post

3. Fetching Data for Dynamic Routes

Dynamic routes shine when paired with real data. Use getStaticPaths and getStaticProps for Static Site Generation (SSG) or getServerSideProps for Server-Side Rendering (SSR).

Example with SSG

Define Routes with getStaticPaths:

1export async function getStaticPaths() {
2  const paths = [
3    { params: { slug: 'my-first-post' } },
4    { params: { slug: 'nextjs-guide' } },
5  ];
6  return { paths, fallback: false }; // Fallback can also be true or blocking
7}

Fetch Data with getStaticProps:

1export async function getStaticProps({ params }) {
2  const post = await fetch(`https://api.example.com/posts/${params.slug}`)
3    .then((res) => res.json());
4
5  return { props: { post } };
6}

1const BlogPost = ({ post }) => {
2  return (
3    <div>
4      <h1>{post.title}</h1>
5      <p>{post.content}</p>
6    </div>
7  );
8};
9
10export default BlogPost;

4. Advanced Dynamic Routes: Catch-All Routing

Catch-all routes ([...slug].js) handle multiple segments dynamically. For instance, a route like /blog/2024/01/my-post can be captured with:

1const BlogPost = () => {
2  const router = useRouter();
3  const { slug } = router.query;
4
5  return <h1>Path: {slug?.join('/')}</h1>;
6};
7
8export default BlogPost;

To generate paths for catch-all routes, update getStaticPaths:

1export async function getStaticPaths() {
2  const paths = [
3    { params: { slug: ['2024', '01', 'my-post'] } },
4    { params: { slug: ['2024', '02', 'another-post'] } },
5  ];
6
7  return { paths, fallback: false };
8}

5. Best Practices for Dynamic Routes

SEO Optimization: Use descriptive slugs, e.g., /blog/nextjs-tips instead of /blog/123.

Fallback Pages: Use fallback: true or blocking to load new routes dynamically without rebuilding.

404 Handling: Create a custom 404.js page in the pages directory for invalid routes.

Prefetch Links: Use next/link to prefetch data for linked pages and improve navigation speed.

Example:

1import Link from 'next/link';
2
3const BlogList = ({ posts }) => (
4  <div>
5    {posts.map((post) => (
6      <Link key={post.slug} href={`/blog/${post.slug}`}>
7        <a>{post.title}</a>
8      </Link>
9    ))}
10  </div>
11);

Conclusion

Dynamic routing is a cornerstone of scalable web applications. By leveraging Next.js features like getStaticPaths and getStaticProps, you can create fast, SEO-friendly pages that cater to diverse data-driven needs. Whether you're building a blog, an e-commerce site, or a dashboard, mastering dynamic routing is essential.

Happy coding! 🚀