Next.js is a popular React framework that enables server-side rendering and static site generation. One of the key features that enhance the development experience in Next.js is its routing system.
While Next.js provides a file-based routing mechanism, implementing nested routes requires some additional understanding. This article will guide you through the process of creating nested routes in Next.js.
What are nested routes?
In Next.js, routing is based on the file system. Each file in the pages
directory corresponds to a route in the application. For example, pages/index.js
maps to the root URL (/
), and pages/about.js
maps to the /about
URL.
Implementation of nested routes in Next.js
Next.js implements routing in the form of a file system where the 'pages' directory is the root directory which corresponds to the path '/'. Nested routes can be introduced in this file system by creating sub-directories inside the 'pages' directory. In the same way, multiple sub-directories can be created within a sub-directory. Thus, the nesting of multiple directories and their routes can be achieved in this way.
Steps To Implement Nested Routes in Next.js
Step 1: Create a next application using the following command.
npx create-next-app@latest <app_name>
The placeholder '<>' specifies the name of the application to be created.
Change the directory to your application directory.
cd <app_name>
Step 2: Install all the required npm dependencies.
npm install
Initial Project Structure: The file structure of our project will look like the following image once the application has been created. Observation of project structure is crucial for our example since Next.js implements file structure-based routing.
initial file structureDependencies
dependencies :
{
"react": "^18",
"react-dom": "^18",
"next": "14.2.4"
}
Example 1: Let's take a basic example to implement nested routing.
Step 1: Create a new directory called 'nested' inside the 'pages' directory.
Step 2: Create a new page called 'index.js' inside the newly created 'nested' directory which will be the root page for the 'nested' directory.
index.js
JavaScript
export default function nested(){
return(
<div>
<h1 style={{color: "green"}}>
Geeks for Geeks
</h1>
<h1> Let's learn nested routing! </h1>
</div>
);
}
Step 3: Create a new page called 'nested_page.js' inside the 'nested' directory.
nested_page.js
JavaScript
export default function nested(){
return(
<div>
<h1 style={{color: "green"}}>
Geeks for Geeks
</h1>
<h1> Nested routing is simple! </h1>
</div>
);
}
After creating nested routes, the project structure will look like this.
project structure after creating a nested routeOutput:
The URL "http://localhost:3000/nested/" will load the root page of the 'nested' directory which is 'index.js'.
The URL "http://localhost:3000/nested/nested_page" will load the page we have nested, inside the 'nested' directory, which is 'nested_page.js'.
Example 2: To get a better understanding of the implementation of nested routing in Next.js, let us take another example of a primitive website of GeeksforGeeks which has a home page (index.js).
Step 1: Replace the content of index.js. For simplicity, let's replace the default index page with a simple GeeksforGeeks home page.
index.js
JavaScript
export default function home(){
return(
<div>
<h1 style={{color: "green"}}>
Geeks for Geeks
</h1>
<h1> Geeks for Geeks home page !!! </h1>
</div>
);
}
Step 2: Create a new page - articles.js (http://localhost:3000/articles)
Let's now create a page for articles on our primitive GeeksforGeeks website. To achieve this, we don't need to implement nested routing since we just need to create the required page under the root directory - 'pages'. So, let's create a page called 'articles.js' under the 'pages' directory.
articles.js
JavaScript
export default function articles(){
return(
<div>
<h1 style={{color: "green"}}>
Geeks for Geeks
</h1>
<h1> Articles page of GeeksforGeeks </h1>
</div>
);
}
Now the file structure looks like this.
file structure after creating articles.jsTill this point, regular routing was able to satisfy our needs.
Step 3: First nested route (http://localhost:3000/articles/dsa). Articles do not come under a single category. Technical articles need to be categorized based on their topics. To achieve this, we need to implement nested routing. This can be done by creating a directory called 'articles' inside the root directory- 'pages' and creating different categories of articles such as 'dsa.js' within the 'articles' directory. The nested route corresponding to the nested directory will be automatically generated by Next.js.
dsa.js
JavaScript
export default function articles(){
return(
<div>
<h1 style={{color: "green"}}>
Geeks for Geeks
</h1>
<h1> Articles page of GeeksforGeeks </h1>
</div>
);
}
The file structure after the creation of our first nested route can be seen below.
first nested routeStep 4: Second nested route (http://localhost:3000/articles/dsa/post1)
Now that we have created a sample category in our project, It's time to add sample posts to it. To do so, we need to create a directory called 'dsa' within the 'articles' directory. Inside the 'DSA' directory, we are going to create our sample post - 'post1.js'.
post1.js
JavaScript
export default function post1(){
return(
<div>
<h1 style={{color: "green"}}>
Geeks for Geeks
</h1>
<h1> Sample post of GeeksforGeeks </h1>
</div>
);
}
The file structure will now look like the one shown below.
NextJs Nested routesOutput:
Steps to run the application: Enter the following command in the terminal to start the development server.
npm run dev
Visit the below URL using a browser: http://localhost:3000/
Similar Reads
Next.js Tutorial
Next.js is a popular React framework that extends React's capabilities by providing powerful tools for server-side rendering, static site generation, and full-stack development. It is widely used to build SEO-friendly, high-performance web applications easily. Built on React for easy development of
6 min read
Next js basics
Next.js Introduction
Next.js is a powerful and flexible React framework that has quickly become popular among developers for building server-side rendered and static web applications. Created by Vercel, Next.js simplifies the process of developing modern web applications with its robust feature set. In this article, weâ
5 min read
Getting Started with Next JS
NextJS is an open-source React framework for building full-stack web applications ( created and maintained by Vercel ). You can use React Components to build user interfaces, and NextJS for additional features and optimizations. It is built on top of Server Components, which allows you to render ser
9 min read
Next.js Installation
Next.js is a popular React framework that enables server-side rendering and static site generation. It is easy to learn if you have prior knowledge of HTML, CSS, JavaScript, and ReactJS. Installing Next.js involves setting up Node.js and npm, creating a new Next.js project using npx create-next-appa
4 min read
NextJS 14 Folder Structure
Next.js, a powerful React framework developed by Vercel, continues to evolve, bringing new features and improvements with each release. Version 14 of Next.js introduces enhancements to the folder structure, making it more efficient for developers to organize their projects. In this article, weâll ex
4 min read
Next.js Create Next App
In Next.js, the create next app command is used to automatically initialize a new NextJS project with the default configuration, providing a streamlined way to build applications efficiently and quickly. System Requirements: Node.js 12.22.0 or laterNPM 6.14.4 or later OR Yarn 1.22.10 or latermacOS,
3 min read
Deploying your Next.js App
Deploying a Next.js app involves taking your application from your local development environment to a production-ready state where it can be accessed by users over the internet. Next.js is a popular React framework that enables server-side rendering, static site generation, and client-side rendering
3 min read
Next js Routing
Next.js Routing
Next.js is a powerful framework built on top of React that simplifies server-side rendering, static site generation, and routing. In this article, we'll learn about the fundamentals of Next.js routing, explore dynamic and nested routes, and see how to handle custom routes and API routes. Table of Co
6 min read
Next.js Nested Routes
Next.js is a popular React framework that enables server-side rendering and static site generation. One of the key features that enhance the development experience in Next.js is its routing system. While Next.js provides a file-based routing mechanism, implementing nested routes requires some additi
5 min read
Next.js Pages
The Next.js Pages are the components used to define routes in the next application. Next.js uses a file-based routing system that automatically maps files in the pages directory to application routes, supporting static, dynamic, and nested routes for seamless web development. In this article, we wil
3 min read
Next JS Layout Component
Next JS Layout components are commonly used to structure the overall layout of a website or web application. They provide a convenient way to maintain consistent header, footer, and navigation elements across multiple pages. Let's see how you can create and use a Layout component in Next.js. Prerequ
3 min read
Navigate Between Pages in NextJS
Navigating between pages in Next.js is smooth and optimized for performance, with the help of its built-in routing capabilities. The framework utilizes client-side navigation and dynamic routing to ensure fast, smooth transitions and an enhanced user experience. Prerequisites:Node.js and NPMReactJSN
3 min read
loading.js in Next JS
Next JS is a React framework that provides a number of features to help you build fast and scalable web applications. One of these features is loading.js which allows you to create a loading UI for your application. Prerequisites:JavaScript/TypeScriptReactJS BasicsNextJSLoading UI is important becau
3 min read
Linking between pages in Next.js
In this article, we are going to see how we can link one page to another in Next.js. Follow the below steps to set up the linking between pages in the Next.js application: To create a new NextJs App run the below command in your terminal: npx create-next-app GFGAfter creating your project folder (i.
3 min read
Next.js Redirects
Next.js Redirects means changing the incoming source request to the destination request and redirecting the user to that path only. When the original web application is under maintenance, the users browse or access the web application, and we want to redirect the user to another web page or applicat
4 min read
Next.js Dynamic Route Segments
Dynamic routing is a core feature in modern web frameworks, enabling applications to handle variable paths based on user input or dynamic content. In Next.js 13+, with the introduction of the App Router, dynamic routes are implemented using a folder-based structure inside the app directory. This art
2 min read
Middlewares in Next.js
Middlewares in Next.js provide a powerful mechanism to execute custom code before a request is completed. They enable you to perform tasks such as authentication, logging, and request manipulation, enhancing the functionality and security of your application. Table of Content Middleware in Next.jsCo
7 min read
Next JS Routing: Internationalization
Next.js allows you to configure routing and rendering for multiple languages, supporting both translated content and internationalized routes. This setup ensures your site adapts to different locales, providing a seamless and localized experience for users across various languages. Prerequisites:NPM
4 min read
How to Reset Next.js Development Cache?
Next.js, a widely used React framework, offers server-side rendering, static site generation, and robust development features. However, cached data in your development environment can sometimes cause issues. Resetting the cache ensures you work with the latest data and code. Letâs explore several me
3 min read
Next js Styling
How to Add Stylesheet in Next.js ?
In Next.js, adding a stylesheet enhances your app's styling capabilities. Import CSS files directly in your components or pages using ES6 import syntax. Next.js optimizes and includes these styles in the build process, ensuring efficient and modular CSS management. In this post, we are going to lear
4 min read
Controlling the specificity of CSS Modules in a Next.js App
CSS Modules are one of the popular techniques that are used for local scoping CSS in JavaScript behavioral applications. In Next.js applications, CSS Modules are mostly used to generate the unique class names for our styles, preventing them from conflicting with the styles from different components
4 min read
Install & Setup Tailwind CSS with Next.js
Tailwind is a popular utility first CSS framework for rapidly building custom User Interfaces. It provides low-level classes, those classes combine to create styles for various components. You can learn more about Tailwind CSS here. Next.js: Next.js is a React-based full-stack framework developed b
3 min read
CSS-in-JS Next JS
CSS-in-JS in Next.js enables you to write CSS styles directly within your JavaScript or TypeScript files. This approach allows you to scope styles to components and leverage JavaScript features, improving maintainability and modularity. In this article learn how to use CSS-in-JS in NextJS its syntax
3 min read
Next.js Styling: Sass
Next.js supports various styling options, including Sass, which allows for more advanced styling techniques like variables, nested rules, and mixins. Integrating Sass into a Next.js project enhances your styling capabilities and makes managing styles more efficient and maintainable. In this article,
3 min read
Next js Optimizing
Next.js Bundle Optimization to improve Performance
In this article, We will learn various ways to improve the performance of the NextJS bundle which results in increasing the performance of NextJS applications in Google PageSpeed Insights or Lighthouse. As per the documentation, NextJS is a React framework that gives you the building blocks to creat
6 min read
Next JS Image Optimization: Best Practices for Faster Loading
Large and unoptimized images can impact a website's performance on loading time. Optimizing images is necessary to improve the performance of the website. Next.js provides built-in support for image optimization to automate the process, providing a balance between image quality and loading speed. Pr
4 min read
Next.js Functions : generateMetadata
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well and back-end. It simplifies React development with powerful features. One of its features is generateMetadata. In this article, we will learn about the generateMetadata function with
3 min read
Lazy Loading in Next.js
Lazy loading in NextJS is a technique used to improve the performance and loading times of web applications built with the NextJS framework. With lazy loading, components or modules are loaded only when they are needed, rather than upfront when the page is initially rendered. This means that resourc
4 min read
How to Add Google Analytics to a Next.js Application?
Adding Google Analytics to a Next.js application allows you to track and analyze your website's traffic and user actions. This can provide valuable insights into how users interact with your site, helping you make informed decisions to improve user experience and drive business goals. This article h
3 min read
Next.js Static File Serving
Next.js allows you to serve static files from the public directory, making them accessible at the root URL. This feature enables easy inclusion of assets like images, fonts, and static HTML files, enhancing your application's functionality and user experience. Static filesAll those files which need
2 min read
Next js Configuring
Next.js TypeScript
NextJS is a powerful and popular JavaScript framework that is used for building server-rendered React applications. . It provides a development environment with built-in support for TypeScript, as well as a set of features that make it easy to build and deploy web applications. It was developed by Z
4 min read
Next.js ESLint
ESLint is a widely-used tool for identifying and fixing problems in JavaScript code. In Next.js projects, integrating ESLint helps ensure code quality and consistency by enforcing coding standards and catching errors early in the development process. In this article, we'll explore how to set up ESLi
3 min read
Next.js Environment Variables
Environment variables are a fundamental aspect of modern web development, allowing developers to configure applications based on the environment they are running in (development, testing, production, etc.). In Next.js, environment variables provide a flexible and secure way to manage configuration s
3 min read
MDX in Next JS
MDXÂ is a lightweight markup language used to format text. It allows you to write using plain text syntax and convert it to structurally valid HTML. It's commonly used for writing content on websites and blogs. In this article we will see more about MDX in Next JS What is MDX?MDX stands for Multidime
4 min read
Next.js src Directory
The NextJS src directory is a project structure that is optional but is widely recommended. It helps to organize the project in a well-defined structure. Organizing a Next.js project with a well-planned folder structure is important for readability, scalability, and maintainability. A clear structur
4 min read
Draft Mode Next.js
Draft Mode in Next.js enables content previewing and editing directly within your application, allowing content creators to view changes before publishing. This feature is especially useful for content management systems or any app where content updates need to be reviewed in real-time. We will expl
5 min read
Next.js Security Headers
Next.js security headers help protect your application from common web vulnerabilities by enforcing security policies at the HTTP level. By configuring these headers, you enhance your app's security and ensure safer interactions for your users. In this article, weâll learn about security headers, th
6 min read
Unit Testing in Next JS: Ensuring Code Quality in Your Project
Unit testing in Next.js ensures that individual components and functions work as expected. It improves code reliability, helps catch bugs early, and facilitates easier maintenance and refactoring by verifying the correctness of isolated units of code. Unit testing is an essential aspect of software
4 min read