Next.js - Nested Routing



Routing is a technique used in web applications to easily navigate between different directories of an application. In this chapter we will explain, what is nested routing and how to implement it in Next.js.

What is Nested Routing?

Nested routing refers to defining routes within other routes, to create a hierarchical structure of routes in a web application. This is a common concept used in frameworks like React.js and Next.js.

Features of Nested Routing

  • Hierarchical Representation: Nested routes represent closely to the hierarchical structure of the UI, making it easy to navigate and build routes in app.
  • Code Reusability: Nested routing helps you to reuse layout components such as headers and sidebars across different child routes.
  • Better User Experience: Nested routing create a seamless transition between related components without reloading the webpage, which helps improve overall user experience of website.

Nested Routing in Next.js

To create nested routes, simply organize your files and folders hierarchically in the /app/ directory. For example, consider following file structure in a Next.js app.

app/
 posts/
     page.jsx
 products/ 
     electronics/ 
         page.jsx 

In this file structure, we can access routes with following URLs:

  • /posts/
  • /products/electronics

Create a Nested Page

To create a nested About page, create a new folder named 'about' inside the /app/ directory and inside that add a file page.tsx with following code.

// app/about/page.js file

export default function About() {
    return (
        <div>
            <h1>About Us</h1>
            <p>Welcome to the about page!</p>
        </div>
    );
}

Output

To see output, visit "http://localhost:3000/about". It will look like this.

Next JS About Page
Advertisements