Next.js routing depends on how we structure the components within the pages folder of our application. Static routes are resolved based on individual file names and directory names. However, we can also create Next.js Dynamic Routes using the same approach along with implementing a catch all route.

If this is your first foray into routing in Next.js, I will recommend you to start with the post on Next.js file based routing.

1 – Creating Next.js Dynamic Routes

Let us assume we have a section in our web application that shows a list of developers with portfolios. To enable such a path, we create a folder portfolio within the pages directory of our project.

For the list page, we can directly create the index.js file within the portfolio directory.

function PortfolioPage() {
    return(
        <div>
            <h1>The Portfolio Page</h1>
        </div>
    )
}

export default PortfolioPage;

Suppose we now want to access the portfolio of a developer by name. When the name changes, the portfolio page also changes. Basically, it is a dynamic route.

In Next.js, we can handle this scenario by creating a file called [name].js inside the portfolio directory. Here, name is nothing but the name of the developer. This could also be an id if we prefer that approach.

Within the [name].js file, we create a new component PortfolioByName.

import { useRouter } from 'next/router';

function PortfolioByName() {
   const router = useRouter();

   console.log(router.pathname);
   console.log(router.query);

   return(
       <div>
           <h1>The Portfolio by Name Page</h1>
       </div>
   ) 
}

export default PortfolioByName;

Here, we are import the useRouter hook from next/router package. This hook is provided as part of the Next.js framework.

Within the component function, we call the useRouter() hook to get access to the router object. The router object is a collection of methods and variables. For our purpose, we are trying to access router.pathname and router.query variables.

We can now run the application and access http://localhost:3000/portfolio/smith. If we inspect the console log, we will see pathname value as /portfolio/[name] and query value as an object {name: 'smith'}. Basically, name is the variable in our dynamic path file.

2 – Next.js Dynamic and Static Path

One of the great aspects of Next.js dynamic path handling is the ability to also use static paths as well. For example, if we want certain portfolio pages to be static in nature, we can declare them with a static file name.

See below example of a static path for Adam’s portfolio.

function AdamPortfolio() {
    return(
        <div>
            <h1>Adam's Portfolio</h1>
        </div>
    )
}

export default AdamPortfolio;

The name of the file is adam.js and we place it in the portfolio directory.

Now, when we run the application and access http://localhost:3000/portfolio/adam, we are routed to Adam’s portfolio page rather than the [name].js dynamic page.

This gives us tremendous flexibility to design our route paths the way we want to.

3 – Next.js Catch All Route

In Next.js, we can also create a catch all route. This is particularly effective if we are not sure about the exact complete path.

For example, what if we can fetch a portfolio just by name such as http://localhost:3000/portfolio/smith and also using a bigger URL such as http://localhost:3000/portfolio/2020/12/smith. As you can see, the second URL also has the year and month in the path.

To handle such a situation using just one component, we can implement a catch all route. In Next.js, we can create a catch all route by creating a file named [...slug].js. Below is the component definition for the same.

import { useRouter } from 'next/router';

function PortfolioByName() {
   const router = useRouter();

   console.log(router.pathname);
   console.log(router.query);

   return(
       <div>
           <h1>The Portfolio by Name Page</h1>
       </div>
   ) 
}

export default PortfolioByName;

As you can see, nothing changes within the component definition.

If we now run the application and access the URL, http://localhost:3000/portfolio/2020/12/smith, we will see that the router.query contains a property slug with an array ["2020", "12", "smith"]. Basically, the path has been broken up and each piece stored as an element of the array.

In case, we don’t go with the URL containing year and month, we still get an array but with only one element i.e. smith. Basically, our component is known flexible enough to handle both types of URL.

Conclusion

Next.js dynamic routing is extremely flexible way of building your application. Along with the implementation of catch-all routes, you can make a pretty simple structure in your pages folder to manage the various paths.

While using dynamic routes, we can also have static paths with relative ease in this setup.

Want to build navigation links with Next.js? Check out this post on Next.js Routing with Link Component.

In case you want to build a more realistic app using NextJS, check out this post on building an event management application using NextJS.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: NextJS

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *