Open In App

Next.js Routing

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.



Next Article

Similar Reads