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 StructureFor 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
- 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. - 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.
- 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. - 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. - 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. - Built-In Optimization: Next.js automatically optimizes routing and navigation, ensuring fast page loads and efficient resource usage.
Uses of Next.js Routing
- 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.
- 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.
- 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.
- User Dashboards: Applications with user dashboards can leverage nested routing to create intuitive and organized navigation structures, such as settings, profiles, and activity feeds.
- 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.
- 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.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Stateless (before hooks)
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects