Welcome to the world of Next.js routing! Routing is the backbone of any web application. Its invisible structure allows users to navigate seamlessly through different pages and content. It is crucial in building user-friendly and dynamic web experiences.
Next.js, a popular React framework, has always offered developers a promising solution for achieving 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 has features like shared layouts, nested routing, loading states, error handling, and more.
In this tutorial, we'll learn 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…
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 a component or handler, should run to create the right response.
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 shows a page with a list of products, while https://example.com/about leads to an "About Us" page.
Routing ensures that accurate content is displayed for each URL.
In this section, let's get familiar with some fundamental terminology:
In Next.js, the 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 provide a step-by-step guide for using the Page Router and App Router.
The generation and organization of routes are fundamental differences between the Pages Directory and the App Router. Let’s explore this difference:
The decision between these two highly effective routing techniques will depend on your project's needs and your understanding of the routing concept. However, the App router is recommended.
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 in the image below. Select "No" when prompted, “Would you like to use App Router?”. This ensures that the Pages Directory is configured for your project.
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 the Pages Directory (i.e., Pages Router) is simple. Follow these steps:
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>
);
}
Users can seamlessly explore your site; developers will appreciate how easily routes are organized using folders.
Here's the result:
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:
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.
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.
Here's how to set it up if you choose to use the App router for routing in your Next.js project:
npx create-next-app@latest app-router-app
Before we move further into this tutorial, let’s get a quick overview of the App directory…
Next.js uses a file and folder structure to create web page routes:
Next.js provides a set of special files to create UI with specific behavior in nested routes. See special files:
.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:
Component Hierarchy
To create a route for the root URL (localhost:3000), you can follow these simple steps:
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.
Now, Let's create two more routes: one for the About page and another for the Dashboard page.
export default function About() {
return <h1>This is About Us Page!</h1>;
}
export default function Dashboard() {
return <h1>This is Dashboard Page!</h1>;
}
The home page will be displayed if you visit the root URL, localhost:3000. 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.
To set up nested routes in Next.js, follow these steps:
export default function blog() {
return <h1>Main Blog Page</h1>;
}
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 automatically handles the routing by organizing the files in a nested folder structure. This simplifies the process of creating nested routes and improves the application's overall organization and structure.
To set up dynamic routes in Next.js for a product listing and detail page, follow these steps:
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.
export default function DetailPage() {
return <h1>Product Detail Page</h1>;
}
export default function DetailsPage({params}){
return(
<div>
<h1>Product Details</h1>
<h2>Details About Product : {params.productId}</h2>
</div>
)
}
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 to create dynamic routes in Next.js, you can create flexible and scalable applications that adapt to varying user interactions.
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/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.
To create nested dynamic routes in Next.js, follow these steps:
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, you'll see the expected content displayed by navigating to localhost:3000/products/1/reviews/1 in the browser.
Similarly, exploring other product IDs and review IDs will dynamically show the relevant values in the user interface.
Next.js will automatically respond with an Error: 404 Not Found response when you provide a URL 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.
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, router 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.
In summary, routing is an essential part of web development. It enables users to navigate seamlessly across websites, providing the structure and pathways 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 discussed the key differences between the App router and the Page Router.
By exploring these concepts, you've understood what these tools can do and 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!
Sumaiya Afrin Kanak
Building a successful e-commerce website is no small feat! Especially when you are coding it from scratch. Designing a u
Read MoreVinish Bhaskar
Don't waste time searching for the perfect Next.js setup. We've curated a list of 11+ Next.js boilerplates to try in 2
Read MoreVinish Bhaskar
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