Open In App

Next.js Routing

Last Updated : 28 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Routing in Next.js is a system that maps URLs to files and folders inside the pages/ (or app/ in Next.js 13+) directory. Unlike React (where you need libraries like React Router), Next.js has built-in routing based on the file-system.

  • Every file inside the pages/ folder becomes a route automatically, so you don’t need extra setup.
  • You can make routes with variables (like /user/1, /user/2) using special file names.
  • By putting files in folders, you create sub-routes that help organize big apps.
  • The built-in Link component makes page changes super fast with preloading.
  • You can add redirects, aliases, or SEO-friendly URLs using next.config.js.
  • Next.js takes care of performance so pages load quickly and smoothly.

Types of Routes in Next.js

Next.js provides a powerful file-based routing system that supports static, dynamic, nested, and API routes. This makes navigation easy to implement without relying on external libraries.

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.

// Filename : pages/api/hello.js

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

Advanced Routing

Advanced routing in Next.js includes features like catch-all routes, optional catch-all routes, nested layouts, parallel routes, and intercepting routes (in Next.js 13+). These features give developers more flexibility and control over complex navigation flows.

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

In Next.js, navigation can be handled using the Link component for client-side routing and the useRouter hook for programmatic navigation. These tools make page transitions faster and provide more control over route handling.

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

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.