Next.js Routing: A Complete Beginner Guide

Vinish Bhaskar

Published on:Feb 28 2024

Next.js Routing: A Complete Beginner Guide

Welcome to the world of Next.js routing! Routing is the backbone of any web application. It's the invisible structure that allows users to navigate seamlessly through different pages and content. It plays a crucial in building user-friendly and dynamic web experiences.

Next.js, a popular React framework has always provided developers with a promising solution for achieving both performance and user-friendliness.

In 2024, Next.js introduced a new App Router, which takes routing to the next level. It simplifies and enhances the way you handle navigation in your web applications. It comes with features like shared layouts, nested routing, loading states, error handling, and more.

In this tutorial, we'll get into the fundamental concepts of routing for the web and how to handle routing, explaining what it is, how it works, and why you should care.

Let’s get started…

What Is Routing?

Routing is all about deciding how an application should react when a user asks for a specific URL. When someone clicks a link or enters a URL in their browser, routing figures out which code, usually in the form of a component or handler, should run to create the right response.

Next.js Routing: A Complete Beginner Guide

It is a fundamental concept in web development that enables users to navigate through different pages or views of a web application.

In a website, different URLs often correspond to different content or functionality.

For example, a URL such as https://example.com/products generally show a page with a list of products, while https://example.com/about lead to an "About Us" page.

Routing ensures that accurate content is displayed for each URL.

Routing Terminology

In this section, let's get familiar with some fundamental terminology:

  • Route: It is a defined path or URL pattern that corresponds to a specific page within a web application. Usually, each route has its own unique URL.
  • Route Handler: It is a piece of code responsible for generating the content or response for a specific route. It allows us to create custom request handlers for a given route using the Web Request and Response APIs.
  • Client-Side Routing: In client-side routing, the client (i.e., a web browser) manages the routing completely, avoiding the need to request the entire web page.
  • Server-Side Routing: In server-side routing, the server generates the HTML code for the requested page and then sends it to the Web Browser.
  • Route Parameters: Route parameters allow dynamic values to be part of the URL. For example, in the URL /products/123, "123" could be a route parameter representing a specific product ID.

In Next.js, Pages Router and App Router are two essential components that play a crucial role in the user's navigation. In the next section, we will go through a step-by-step guide on using the Page router and App router.

Pages Router vs. App Router

Next.js Routing: A Complete Beginner Guide

The generation and organization of routes a fundamental differences between the Pages Directory and the App Router. Let’s explore this difference:

  • Pages Router: The Next.js project's Pages directory, which is found at the project's root, automatically generates routes based on the folder and file structures included therein. A separate route is associated with each file in the pages directory. For example, the pages directory has a file named about.js that generates a route that is accessible at /about.
  • App Router: On the other hand, App Router arranges routes inside the app folder. It was included in Next.js version 13 and got stable and recommended from the latest release of version 13.4. It provides for more precise control over route organization and introduces concepts like shared layouts, nested routing, and error handling.

The decision between these two highly effective routing techniques will depend on the needs of your project and your understanding of the routing concept. However, the App router is recommended.

Setting Up the Pages Router

If you decide to use the Pages Router for routing in your Next.js project, follow these steps to set it up:

Create a Next.js Application: Use your terminal or code editor to run the following command to start a new Next.js application:

npx create-next-app your-app-name

Configuration Options: You'll be given a list of configuration options during the application setup process as shown below image. Select "No" when prompted “Would you like to use App Router?”. This ensures that the Pages Directory is configured for your project.

Next.js Routing: A Complete Beginner Guide

Folder Structure: Once your application is created, a pages folder will appear at the project's root. This directory will be the starting point for creating your routes.

Creating routes using Pages Directory

It is simple to create routes using the Pages Directory (i.e. Pages Router). Follow these steps:

  • Create a Folder: Inside the pages directory, create a new folder with the name you want for your route. For example, you can create a folder named `About` to represent an About Us page.
  • Add an index.js File: Create an index.js file inside the newly created folder. This file will contain the content for the route.
  • Content Creation: In the index.js file, build your page's content using React components and JSX. This content will be displayed when users navigate to the /about route.
import Link from 'next/link';

export default function About() {
  return (
    <div className="flex justify-center items-center h-screen">
      <div>
        <h1 className="text-2xl font-bold mb-4">This is About Us Page</h1>
          <Link className="bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600" href="/">Home Page</Link>
      </div>
    </div>
  );
}
  • Linking Pages: You may use the Next.js Link component to make it easier to navigate across pages. You can build links using this component. It will help users switch between pages without requiring a page refresh.
Next.js Routing: A Complete Beginner Guide

Users can seamlessly explore your site, and developers will appreciate how easily routes are organized using folders.

Here's the result:

Next.js Routing: A Complete Beginner Guide

Limitations

While the Pages Directory offers an efficient way to structure routes in a Next.js application, it's important to be aware of its limitations:

  • Static Exports: One of the primary limitations of the Pages Directory is static exports. The Pages Directory relies on dynamic routes generated using getStaticProps and getStaticPaths. Not all pages within the directory can be statically exported, depending on their data requirements.
  • Serverless Functions: Next.js allows to creation of API routes within the Pages Directory, It can handle common API functionality, but more complex serverless functions might require additional configuration and alternative file placement.
  • Statically Generated Pages Distribution: Statically generated pages may require additional CDN configuration or "vendoring" to optimize their performance and distribution to visitors.
  • Edge Runtime Configuration: If you're using the Edge Runtime, you may need to configure routes beyond what's possible within the Pages Directory.
  • Internationalization Routing: To implement internationalization routing effectively, you need to configure locales, default locales, and domain-specific locales. These configurations typically reside in the next.config.js file rather than being solely managed within the Pages Directory.

Understanding these limitations will help you make informed decisions when choosing between routing in your Next.js projects. Each mechanism has its own strengths and uses cases.

App Router

Next.js Routing: A Complete Beginner Guide

A new App Router was introduced in Next.js version 13.0, built on React Server Components. Which supports shared layouts, nested routing, loading states, error handling, and more. The recent release of Next.js 13.4 marked a significant accomplishment: the new App Router is now production-ready.

It allows you to organize your project more flexibly and efficiently. Instead of being restricted to just a "pages" folder, you can group your pages and related files within a single "app" folder.

In this section, you will learn how to create the Next.js project using the App Router and lots more about App Router.

How to Setup the App Router

Here's how to set it up if you choose to use the App router for routing in your Next.js project:

  • Create a Next.js Application: Use your terminal or code editor to run the following command to start a new Next.js application:
npx create-next-app@latest app-router-app
  • Configuration Options: You'll be given a list of configuration options during the application setup process as shown below image. Select "Yes" when prompted “Would you like to use App Router?”. This ensures that the App Router is configured for your project.
Next.js Routing: A Complete Beginner Guide
  • App Router: Once your application is created, an app folder will appear at the project's root. This directory will be the starting point for creating your routes.

Before we move further into this tutorial, let’s get a quick overview of the App directory…

Roles of Folders and Files

Next.js uses a file and folder structure to create web page routes:

  1. Folders Define Routes: Each folder represents a different page or part of your website. The folders can be nested inside each other to create a hierarchy, just like organizing your files on your computer.
  2. Files Create Content: Inside these folders, files contain the actual content or user interface (UI) for each page or section.

Next.js provides a set of special files to create UI with specific behaviour in nested routes. See special files:

  • Layout: Shared UI for multiple pages
  • Page: The content and UI for a specific webpage
  • Loading: UI displayed during data loading
  • Not-Found: UI is shown when a page or route doesn't exist
  • Error: UI for handling errors and issues
  • Global Error: UI for handling errors across the whole app
  • Route: A server-side API endpoint for data and actions
  • Template: Specialized layout for certain types of pages
  • Default: Fallback UI when multiple routes match a URL

.js, .jsx, or .tsx file extensions can be used for special files.

Special files of a route segment are rendered in a specific hierarchy, Here it is:

Next.js Routing: A Complete Beginner Guide

Component Hierarchy

Creating a route

To create a route for the root URL (localhost:3000), you can follow these simple steps:

  • Inside the app folder, create a page.jsx file if doesn't exist. This file will serve as the home route.
  • In the page.jsx file, create or modify it with a basic React component to represent the "Home" page:
export default function Home() {
  return <h1>This is Home Page!</h1>;
}

By following the above steps, we have successfully created our first route. Now, open your web browser and visit localhost:3000 to see the "This is Home Page!" message.

Adding Routes

Now, Let's proceed to create two more additional routes: one for the About page and another for the Dashboard page.

  • Create an app/about folder.
  • Inside the about folder, create a page.jsx file. This file represents the route.
  • On the page.jsx file, define a basic component to represent the "About Us" page:
export default function About() {
    return <h1>This is About Us Page!</h1>;
  }
  • Similarly, create an app/dashboard folder.
  • Inside the dashboard folder, create a page.jsx file. This file represents the route.
  • On the page.jsx file, define a basic component to represent the "Dashboard" page:
export default function Dashboard() {
    return <h1>This is Dashboard Page!</h1>;
  }

Next.js Routing: A Complete Beginner Guide

If you visit the root URL, localhost:3000, the home page will be displayed. However, if you visit localhost:3000/about, the "About Us" page will be displayed. Similarly, /dashboard URL will show the "Dashboard" page.

This shows how routes are linked to files based on the name of the contained folder inside the app folder. The page.jsx file within the about folder represents /about, while the page.jsx file within the dashboard folder represents /dashboard.

Nested Route

To set up nested routes in Next.js, follow these steps:

  • Create an app/blog folder or whatever name you want.
  • Inside the blog folder, create a page.jsx file for the main page of the blog:
export default function blog() {
    return <h1>Main Blog Page</h1>;
  }
  • Visit localhost:3000/blog in the browser to see the "Main Blog" page.
  • To implement /blog/firstPage and /blog/secondPage routes, create page.jsx files in the app/blog/firstPage and app/blog/secondPage folders with the following code:
export default function firstPage() {
    return <h1>Blog First Page</h1>;
  }
export default function secondPage() {
    return <h1>Blog Second Page</h1>;
  }

The folder structure will look like this:

Next.js Routing: A Complete Beginner Guide
  • Now, when you navigate to localhost:3000/blog/firstPage, you'll see the first page of the blog post, and localhost:3000/blog/secondPage will display the second page of the blog post.

By organizing the files in a nested folder structure, Next.js automatically handles the routing. This simplifies the process of creating nested routes and improves the overall organization and structure of the application.

Dynamic Route

To set up dynamic routes in Next.js for a product listing and detail page, follow these steps:

  • Create an app/products folder.
  • Inside the products folder, create a page.jsx file to display a list of the products:
export default function ProductPage() {
    return (
      <>
        <h1>Product List</h1>
        <h2>Product 1</h2>
        <h2>Product 2</h2>
        <h2>Product 3</h2>
      </>
    );
  }

Visit localhost:3000/products in the browser, The Products list will be displayed on the screen.

  • For the product detail page, create a new folder within the products folder and name it [productId]. The square brackets indicate a dynamic route.
  • Inside the [productId] folder, create a page.jsx file:
export default function DetailPage() {
    return <h1>Product Detail Page</h1>;
  }
  • Now, when you navigate to localhost:3000/products/1, you'll see the product details page. Similarly, accessing /products/2, /products/3, or even /products/100 will display the same details page. [productId] is the dynamic route segment that can adapt values like 1, 2, 3, and so on.
  • To display the specific product ID, use the params object to display on each page. Modify the code as below:
export default function DetailsPage({params}){
    return(
        <div>
            <h1>Product Details</h1>
            <h2>Details About Product : {params.productId}</h2>
        </div>
    )
}

Now, when you navigate to localhost:3000/products/1, you'll see "Details about product 1" displayed. Similarly, /products/100 will show details about “Product 100."

Dynamic routes help create list-detail patterns in UI apps. By learning how to create dynamic routes in Next.js, you can create flexible and scalable applications that adapt to varying user interactions.

Nested Dynamic Route

In the previous section, we covered dynamic routes, and now, we'll learn about nested dynamic routes.

Nested dynamic routes in Next.js allow us to create complex and dynamic URL structures by combining multiple dynamic route segments.

For example, when visiting to /products/1, users expect to view details for product 1. Likewise, visiting /products/1/reviews/1 should show the first review of that product.

We'll explore how to achieve this using the App Router.

Next.js Routing: A Complete Beginner Guide

To create nested dynamic routes in Next.js, follow these steps:

  • Create an app/products/[productId]/reviews folder. This structure leads to the route "/products/productId/reviews." We also need a dynamic reviewId to show specific reviews.
  • Within the reviews folder, create a new folder named [reviewId]. Once again, the square brackets indicate a dynamic route.
  • Inside the [reviewId] folder, create a page.jsx file, here we'll create a component to display both the productId and the reviewId of the product:
export default function ReviewPage({params}){
    return(
        <div>
            <h1>Review Page</h1>
            <h2>Product Id : {params.productId}</h2>
            <h2>This is Review : {params.reviewId} of Product : {params.productId}</h2>
        </div>
    )
}

Now, by navigating to localhost:3000/products/1/reviews/1 in the browser, you'll see the expected content is displayed. Similarly, exploring other product IDs and review IDs will dynamically show the relevant values in the user interface.

Handling Non-Matching Route

Next.js will automatically respond with an Error: 404 Not Found response when you provide a URL that is not available within the app folder, such as /profile. Since Next.js takes care of this for you, you don't need to manually handle non-matching routes.

Advanced Features of App Router in Next.js

The App Router in Next.js offers advanced features that go beyond what we've discussed so far. It includes features such as File colocation, Private folders, Route groups, server actions, data revalidation, parallel routes, and route interception, which add more functionality to your application.

For a better understanding and mastery of these features, you can refer to the official Next.js documentation, which provides comprehensive information on these features in Next.js.

Conclusion

In summary, routing is an essential part of web development. It enables users to navigate seamlessly across websites, providing the structure and pathways needed to access different pages and content.

In this tutorial, we explored the basics of routing in Next.js 13 and learned how to structure routes using both the Pages Router and the App Router. We specifically focused on the stable App router introduced in the latest version Next.js 13.4.

We discussed routing terminology, learned about specific files, created routes for different aspects, and also discussed about key differences between the App router and the Page Router.

By exploring these concepts, you've not only understood what these tools can do but also got an idea about when to use the App Router and when to stick with the old way of using the Pages Directory.

Stay tuned for more exciting tutorials!

Tags:
Share This Post

Related Articles

21+ Best Next.js Admin Dashboard Template for 2024

21+ Best Next.js Admin Dashboard Template for 2024

Are you looking for an Admin Dashboard Template for your Next.js project? Look no further! We've curated a list of 21+

Read More
21+ Best Headless CMS for Next.js in 2024

21+ Best Headless CMS for Next.js in 2024

Are you looking for a headless CMS for Next.js website? But confused about which one to choose. We know the struggle of

Read More
Next.js vs Nuxt: Which one is Better in 2024?

Next.js vs Nuxt: Which one is Better in 2024?

Hey developers 👋, thanks for stopping by! Imagine you're in a cool superhero movie, and you get to pick your coding her

Read More