The Wayback Machine - https://web.archive.org/web/20240919123219/https://www.geeksforgeeks.org/next-js-routing/
Open In App

Next.js Routing

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

What is Next.js Routing?

Next.js offers a simple and intuitive way to manage routing using a file-based system. Each file in the pages directory automatically becomes a route, eliminating the need for complex routing configurations.

Types of Routes in Next.js

  • Static Routes
  • Nested Routes
  • Dynamic Routes
  • API Routes

Static Routes

All the files in our pages directory having .js, .jsx, .ts and .tsx are automatically routed. The index.js is the root directory. For Example: If we create a file in the pages directory named index.js. Then it could be accessed by going to http://localhost:3000/

// pages/index.js.js

const Home = () => {
return(
<div>
Home Page
</div>
);
}
export default Home;

Nested Routes

If we create a nested folder structure, our routes will also be structured in the same manner. For Example:  If we create a new folder called users and create a new file called about.js within it, we can access this file by visiting http://localhost:3000/users/about

// pages/user/About.js

const About = () => { 
    return(
        <div>
            About Page
        </div>
    );
}
export default About;

Dynamic Routes

We can also accept URL parameters and create dynamic routes using the bracket syntax. For Example: If we create a new page in the pages directory called [id].js then the component exported from this file, could access the parameter id and render content accordingly. This can be accessed by going to localhost:3000/<Any Dynamic Id>.

// pages/users/[id].js

import { useRouter } from 'next/router'; const User= () => { const router = useRouter(); const { id } = router.query; return <p>User: {id}</p>; }; export default User;

API Routes

Next.js supports creating API Routes/endpoints by adding files under the pages/api directory. Each file in this directory is mapped to an API endpoint.

Example:

// Filename : pages/api/hello.js

export default function handler(req, res) {
    res.status(200).json({ message: 'Hello, world!' });
}

Advanced Routing

Catch-All Routes

We can catch all paths in Next.js using catch-all routes. For this, we have to add three dots inside the square brackets in the name of the file as shown below:

./pages/[...file_name].js

Optional Catch-All Routes

Optional catch-all routes in Next.js extend the concept of catch-all routes by allowing you to handle routes with a variable number of segments, including the option of no segments at all.

We can make catch-all routes optional in NextJS using optional catch-all routes. For this, we have to add three dots inside the double square brackets in the name of the file. For example:-

./pages/[[...file_name]].js

Linking Between Pages

We can navigate between pages using the Link component from the next/link module. This component enables client-side navigation between pages in the NextJS application. It provides a smoother user experience compared to traditional full-page reloads.

useRouter hook

The useRouter hook allows you to access the Next.js router object and obtain information about the current route, query parameters, and other route-related details.

import { useRouter } from 'next/router ';

function MyComponent() {
 
    //Main Syntax
    const router = useRouter();

    // Accessing route information using router object
    console.log(router.pathname); // Current route
    console.log(router.query);    // Query parameters

    return (
        // Your component JSX
    );
}

Steps to Implement Next.js Routing

Step 1: Run the following command to Create a new Next Application.

npx create-next-app myproject

When we open our app in a code editor we see the following project structure.

Project Structure:

Next.js Folder Structure

For the scope of this tutorial, we will only focus on the pages directory. When we initialize our Next App, we get a default index route. It works as a homepage for our application. Now we’ll set up three different routes to test all the route types in Next Js. 

Make a new folder called users in the pages directory called users, then make three new files in the user’s folder: [id].js, index.js, and about.js. We will also use the Link component to create navigation on our homepage to access these routes.

JavaScript
//pages/index.js

import React from "react";
import Link from "next/link";
const HomePage = () => {
    // This is id for dynamic route, you
    // can change it to any value.
    const id = 1;
    return (
        <>
            <h1>Home Page</h1>
            <ul>
                <li>
                    <Link href="/users">
                        <a>Users</a>
                    </Link>
                </li>
                <li>
                    <Link href="/users/about">
                        <a>About Users</a>
                    </Link>
                </li>
                <li>
                    <Link href={`/users/${id}`}>
                        <a>User with id {id}</a>
                    </Link>
                </li>
            </ul>
        </>
    );
};

export default HomePage;
JavaScript
//pages/users/index.js

import React from "react";

const Users = () => {
    return <h1>Users Page</h1>;
};

export default Users;
JavaScript
//pages/users/about.js

import React from 'react'

const Users = () => {
    return (
        <h1>Users About Page</h1>
    )
}

export default Users
JavaScript
//pages/users/[id].js

import React from 'react'
import { useRouter } from 'next/router'

const User = () => {
    const router = useRouter()
    return 
        <h1>
            User with id 
            {router.query.id}
        </h1>
}

export default User;

Step to run the application: Run your Next.js app using the following command: 

npm run dev

Output

Features of Next.js Routing

  1. File-Based Routing: Next.js uses a file-based routing system where each file in the pages directory corresponds to a route in the application. This makes it easy to manage routes without complex configurations.
  2. Dynamic Routing: You can create dynamic routes using parameterized file names, allowing you to handle routes with dynamic segments, such as user profiles or blog posts.
  3. Nested Routing: Nested routes are supported through a simple directory structure. Subdirectories inside the pages directory create nested routes, making it easy to organize and manage complex route hierarchies.
  4. Client-Side Navigation: The built-in Link component enables fast client-side navigation with prefetching capabilities, improving the performance and user experience of your application.
  5. Custom Routes: You can define custom routes, aliases, and redirects in the next.config.js file, allowing you to create more flexible and SEO-friendly URLs.
  6. Built-In Optimization: Next.js automatically optimizes routing and navigation, ensuring fast page loads and efficient resource usage.

Uses of Next.js Routing

  1. Static Websites: Next.js routing is ideal for building static websites where each page corresponds to a specific file. This approach simplifies development and deployment.
  2. Blogs and Content-Driven Sites: Dynamic routing and nested routes make it easy to create blogs and content-driven sites with complex navigation structures, such as categories and tags.
  3. E-commerce Platforms: E-commerce platforms can benefit from dynamic routes for product pages, nested routes for product categories, and API routes for handling backend logic like user authentication and payment processing.
  4. User Dashboards: Applications with user dashboards can leverage nested routing to create intuitive and organized navigation structures, such as settings, profiles, and activity feeds.
  5. Full-Stack Applications: Next.js routing, combined with API routes, allows developers to build full-stack applications with both frontend and backend logic in a single project, simplifying development and deployment.
  6. Single Page Applications (SPAs): With client-side navigation and prefetching capabilities, Next.js is well-suited for building SPAs that require fast and seamless transitions between pages.

Conclusion

Next.js’s file-system-based routing is powerful and intuitive, allowing developers to create static, dynamic, nested, and API routes effortlessly. With support for advanced features like catch-all routes and a built-in Link component for navigation, Next.js simplifies the process of building scalable and high-performance web applications.



Previous Article
Next Article

Similar Reads

What is Routing and Nested Routing in Angular 9/8 ?
In this article, we will learn the routing &amp; nested routing concept in Angular. We will implement the concept to establish routing between different components by making their routes when a user clicks the link, it will be navigated to a page link corresponding to the required component. Let's understand the routing in Angular. Routing: Angular
5 min read
Mastering React Routing: Learn Navigation and Routing in React Apps
In this article, we will learn how to implement Routing in React in an efficient way by implementing various aspects of routing such as dynamic routing, programmatically routing, and other concepts. Table of ContentWhat is Navigation in React?Routing with no page found(error 404) error handlingProgrammatic Navigation in ReactDynamic Routing with Re
6 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 &amp; NodeJSReactJSNextJSJavaScriptInternationali
4 min read
How to pass variables to the next middleware using next() in Express.js ?
The following example covers how to pass variables to the next middleware using next() in Express.js. Approach: We cannot directly pass data to the next middleware, but we can send data through the request object. [Middleware 1] [Middleware 2] request.mydata = someData; -------&gt; let dataFromMiddleware1 = request.mydata; Installation of Express m
2 min read
Next.js next/head
In this article, we'll learn about the Head component in NextJS and see how the head component is SEO friendly. The Head component is a built-in component provided by NextJS. We can add any element like we were adding in the head component of HTML. If you know HTML and CSS well then NextJS will be easy for you to learn. To keep everything simple th
4 min read
When to use next() and return next() in Node.js ?
In Node.js, particularly when working with the Express framework, middleware functions play a crucial role in handling requests. Two commonly used patterns within these middleware functions are next() and return next(). Understanding when and how to use these can significantly affect the flow and functionality of your application. Table of Content
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, Windows, and Linux are supportedGetting started wi
3 min read
Next.js next/link
In Next.js, next/link component enables client-side navigation between pages, enhancing performance by prefetching linked pages. It simplifies routing in your application, making it seamless and efficient. Table of Content Next.js next/link ComponentBasic usage of 'next/link'Dynamic routing with 'next/link'ConclusionNext.js next/link ComponentThe n
4 min read
Next.js next/amp
AMP (Accelerated Mobile Pages) is a web component framework developed by Google that enables the creation of fast-loading web pages. Next.js supports AMP out of the box, allowing you to create AMP pages seamlessly. What is Next.js AMP?AMP is designed to improve the performance of web pages, particularly on mobile devices. By using a subset of HTML
3 min read
Next.js next.config.js File
The next.config.js file in a Next.js application is a configuration file used to customize and extend the behavior of Next.js. It allows developers to adjust various settings such as routing, environment variables, image optimization, and more to tailor the application to their specific needs. What is next.config.js?The next.config.js is a configur
3 min read
Routing in Angular JS using Angular UI Router
AngularJS is a front-end web application framework based on JavaScript and is maintained by Google. AngularJS interprets the attributes of HTML as directives to bind input/output components to a model represented by standard JavaScript variables. Pre-requisites: HTML CSS JavaScript AngularJS Angular-UI-Router is an AngularJS module used to create r
3 min read
AngularJS Routing
Routing in AngularJS is used when the user wants to navigate to different pages in an application but still wants it to be a single-page application. AngularJS routes enable the user to create different URLs for different content in an application. The ngRoute module helps in accessing different pages of an application without reloading the entire
3 min read
Routing Path for ExpressJS
What and Why ? Routing in ExpressJS is used to subdivide and organize the web application into multiple mini-applications each having its own functionality. It provides more functionality by subdividing the web application rather than including all of the functionality on a single page. These mini-applications combine together to form a web applica
3 min read
Laravel | Routing Basics
Once you have installed Laravel and your basic Web App is up and running. Let's just look more deeply into the framework and see how we can work with routes. Routes: Routes are actually the web URLs that you can visit in your web application. For example /home, /profile, /dashboard etc are all different routes that one can create in a Laravel Appli
4 min read
How to put an image as background under multiple components in ReactJS with React Routing?
We can make a parent component and use that parent component to wrap the child component so that the parent component appears as an image overlay above the child component. Syntax: &lt;div style={{ backgroundImage: `url(${'/background.jpg'})`}}&gt; {props.children} &lt;/div&gt; Creating React Application: Step 1: Create a React application using th
2 min read
How to setup 404 page in angular routing ?
To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent. Creating Component: Run the below command to create pagenotfound component. ng generate component pagenotfoundProject Structure:
2 min read
Routing in Angular 9/10
Routing in Angular allows the users to create a single-page application with multiple views and allows navigation between them. Users can switch between these views without losing the application state and properties. Approach: Create an Angular app that to be used.Create the navigation links inside the app component and then provide the "routerLin
3 min read
How to use routing in Vue.js ?
Vue router: Vue Router helps link between the browser's URL/History and Vue's components allowing for certain paths to render whatever view is associated with it. A vue router is used in building single-page applications (SPA). The vue-router can be set up by default while creating your new project. In this article, we will install it separately. S
3 min read
How to create module with Routing in Angular 9 ?
Angular applications are modular, and NgModules is Angular's own modular architecture. NgModules are containers for closely integrated application domains, workflows, or feature sets that comprise cohesive code blocks. Their scope is governed by the NgModule they include, and they can contain components, service providers, and other code files. You
4 min read
Flask App Routing
App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL ("/") is associated with the root URL. So if our site's domain was www.example.org and we want to add rout
3 min read
Routing in Nuxt.js
In this article, we are going to learn how routing works in NuxtJs. Nuxt.js is a free and open-source web application framework based on Vue.js, Node.js, Webpack, and Babel.js. Nuxt is inspired by Next.js, which is a framework of a similar purpose, based on React.js. Create NuxtJS Application: Step 1: You can create a new Nuxt.js project using the
2 min read
Gatsby Routing
Gatsby is a free and open-source framework based on React that helps developers build blazing-fast websites and apps. Gatsby's sites are fully functional React apps, so you can create dynamic web applications that are fast, responsive, and secure. Introduction: When building a website, one of the most important aspects is routing. Routing is the pr
3 min read
How is React Router is different from conventional routing ?
React Router is a library for routing in React applications. It allows you to create routes and link to them from your components. When a user clicks a link, React Router will determine which route to use and render the corresponding component. Prerequisites:NodeJS or NPMReact JSReact RouterSteps to Create the React Application And Installing Modul
2 min read
How to setup 404 page in React Routing ?
Every Website needs a 404 page if the URL does not exist or the URL might have been changed. To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurs. In the following approach, we will create a simple react component called PagenotfoundComponent.  Prerequisites:NPM &amp; Node JSReact J
2 min read
React MUI Routing
React MUI is a UI library that provides fully-loaded components, bringing our own design system to our production-ready components. MUI is a user interface library that provides predefined and customizable React components for faster and easy web development, these Material-UI components are based on top of Material Design by Google. In this articl
3 min read
Routing in Node
What is Routing in Node ?Routing defines how the client requests are handled by the application endpoints. Routing in Node refers to the process of determining how an application responds to client requests to different endpoints (URLs). In a web application, these endpoints typically correspond to different pages or functionalities within the appl
3 min read
What is routing in React?
Routing in React refers to the process of managing and navigating between different views or pages in a single page application (SPA). Unlike traditional multi-page applications where each page is a separate HTML document, SPAs load a single HTML page and dynamically update the content as the user interacts with the application. React applications
2 min read
What is routing in Express?
Express routing is about showing your app how to respond to different URLs. It involves associating HTTP methods with specific functions to handle requests. This helps organize and control the flow of your web application. Routing in Express:Routing in Express is like showing your web app where to go.It's about deciding what your app should do when
2 min read
How to handle routing with Hooks?
You can handle routing with hooks using libraries like React Router. It allows you to define different routes for different components and manage navigation between them. React Router provides several hooks for handling routing within functional components, such as useHistory and useNavigate. Key Features of React Router:Declarative Routing: React
2 min read
How to use Angular MatTabsModule with routing in Angular 17?
The Angular Material library provides a tab component called MatTabsModule that allows you to organize content into separate tabs. When combined with Angular routing, you can create a seamless navigation experience where each tab loads its content from a different route. In this article, we'll explore how to use MatTabsModule with routing in an Ang
4 min read