Next.js Routing: Exploring Client-Side, Dynamic, and Nested Routes

Next.js Routing: Exploring Client-Side, Dynamic, and Nested Routes

ยท

3 min read

If you're building a website with Next.js, one of the crucial features you'll need is routing. Next.js offers a range of powerful routing options, including client-side, dynamic, and nested routes. In this article, we'll take a closer look at each of these route types and explore how to implement them using Next.js.

Client-Side Routing with Next.js

Client-side routing is one of the most basic routing types in Next.js. In client-side routing, the client navigates between pages without having to make a request to the server for a new page. To implement client-side routing in Next.js, we can use the <Link> component.

Here's an example showing how to use the <Link> component to navigate to another page:

import Link from 'next/link';

function Home() {
  return (
    <div>
      <h1>Home</h1>
      <ul>
        <li><Link href="/about">About</Link></li>
        <li><Link href="/blog">Blog</Link></li>
      </ul>
    </div>
  );
}

In this example, we import the Link component and use it to create links to the /about and /blog pages.

Dynamic Routing with Next.js

Dynamic routing is the process of generating a page based on a parameter in the URL. With Next.js, dynamic routing is easy to implement using the getStaticProps and getStaticPaths methods. These methods allow you to fetch data for a dynamic route at build time, rather than runtime, resulting in significantly faster page loads and improved performance.

Here's an example showing how to use dynamic routing with Next.js:

export async function getStaticPaths() {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();

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

  return { paths, fallback: false };
}

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

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

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

export default Post;

In this example, we use getStaticPaths to fetch a list of all posts and generate an array of paths to pre-render at build time. We then use getStaticProps to fetch the data for the post with the specified id parameter.

Nested Routing with Next.js

Nested routing is another powerful feature of Next.js. It allows you to create nested pages or sections within a website. Implementing nested routing in Next.js is easy to do using the useRouter hook. This hook provides a range of information about the current route, which you can then use to build out nested routes.

Here is an example showing how to use the useRouter hook and nested routing in Next.js:

import { useRouter } from 'next/router';

function CategoryPage() {
  const router = useRouter();
  const { category } = router.query;

  return (
    <div>
      <h1>{category}</h1>

      <ul>
        <li><a href={`/category/${category}/item1`}>Item 1</a></li>
        <li><a href={`/category/${category}/item2`}>Item 2</a></li>
      </ul>

      {router.query.item && (
        <div>
          <h2>{router.query.item}</h2>
          <p>Content for {router.query.item}</p>
        </div>
      )}
    </div>
  );
}

export default CategoryPage;

In this example, we use the useRouter hook to get information about the current route, including the category and item parameters. We then use this information to build out the nested routes and display the appropriate content based on the parameters.

Conclusion

Routing is a critical feature of any website or web app, and Next.js provides a range of powerful routing options. In this article, we explored client-side, dynamic, and nested routing in Next.js, along with code examples showing how to implement each type. Whether you're building a simple website or a complex web app, Next.js has the routing tools you need to create a smooth and intuitive user experience.

๐Ÿ™Œ Follow me on:

Did you find this article valuable?

Support Simple Dev by becoming a sponsor. Any amount is appreciated!

ย