Skip to main content

Step-by-Step Tutorial: Implementing Not Found Pages (404) and Route Grouping in Next.js

In this blog, we will explore the concept of not found pages and route grouping in Next.js. When users navigate through our application, there may be instances where they land on a page that doesn't exist or enter a random path. By default, Next.js provides a built-in 404 page for these scenarios. However, we can also create our own custom not found page to provide a more meaningful experience for our users.

Creating a Custom Not Found Page

Next.js follows a specific file naming structure for its application. To create a custom not found page, we need to create a file named "not-found.tsx" in the "app" folder. This file should adhere to the specified naming pattern to work properly. Let's dive into the steps:

Step 1: File Structure

First, navigate to the "app" folder and create a new file named "not-found.tsx". This file will serve as our custom not found page. Make sure to follow the specified naming pattern for Next.js to recognize it.

Step 2: Creating the Component

Now, let's export a plain component from the "not-found.tsx" file. You can use the following code as a starting point:

  • import React from 'react';
  • const NotFound = () => {
  • return (
  • The page you're trying to access is not available or incorrect.

  • );
  • }
  • export default NotFound;

In this example, we have a simple message that will be displayed when the user enters a random path in our application. Feel free to customize the message according to your needs.

Step 3: Implementing the Custom Not Found Page

Now that we have our custom not found page ready, let's see how it works. If a user enters a path that does not exist in our application, Next.js will automatically use the "not-found.tsx" file to render the page. The user will see the custom message we defined instead of the default 404 page provided by Next.js.

Let's test it out. Type a random path in the URL and hit enter. You should now see the message "The page you're trying to access is not available or incorrect." instead of the default Next.js 404 page.

Route Grouping in Next.js

In addition to handling not found pages, Next.js also provides a feature called route grouping. Route grouping allows us to organize our routes into separate files, making our code more modular and maintainable.

In a typical Next.js application, we have multiple URLs and corresponding paths. With route grouping, we can group these paths and their respective components into separate files, improving the overall structure of our project.

Let's take a closer look at how route grouping works:

Step 1: File Structure

To implement route grouping, we need to organize our files in a specific folder structure. Create a new folder named "routes" in the root directory of your Next.js project.

Step 2: Creating Route Files

Within the "routes" folder, create separate files for each group of routes. For example, if you have routes related to authentication, create a file named "auth.tsx". Similarly, create files for other groups such as "dashboard.tsx", "admin.tsx", etc.

Step 3: Implementing Routes

Inside each route file, define the paths and their corresponding components using the Next.js routing syntax. For example:

  • import React from 'react';
  • import { Route } from 'next/router';
  • import AuthPage from '../pages/AuthPage';
  • const authRoutes = [
  • {
  • path: '/login',
  • component: AuthPage,
  • },
  • {
  • path: '/signup',
  • component: AuthPage,
  • },
  • ];
  • const AuthRoutes = () => {
  • return (
  • {authRoutes.map((route) => (
  • ))}
  • );
  • }
  • export default AuthRoutes;

In this example, we have created an "auth.tsx" file to group authentication-related routes. We define an array of objects, where each object represents a path and its corresponding component. The "AuthRoutes" component renders the routes dynamically using the Next.js routing syntax.

Step 4: Implementing Route Grouping

Now that we have our route files ready, let's implement route grouping in our Next.js application. In the main routing file (usually named "routes.tsx" or "index.tsx"), import and render the route group components. For example:

  • import React from 'react';
  • import AuthRoutes from '../routes/auth';
  • import DashboardRoutes from '../routes/dashboard';
  • const Routes = () => {
  • return (
  • <div>
  • <AuthRoutes />
  • <DashboardRoutes />
  • </div>
  • );
  • }
  • export default Routes;

In this example, we import the "AuthRoutes" and "DashboardRoutes" components from their respective route files and render them in the main component. This way, we can easily manage and maintain our routes, keeping them organized and modular.

Conclusion

In this blog, we explored the concepts of not found pages and route grouping in Next.js. By creating a custom not found page, we can provide a more meaningful experience to users when they encounter non-existent pages. Additionally, route grouping allows us to organize our routes into separate files, improving the structure and maintainability of our Next.js applications.

Next.js offers powerful features and flexibility when it comes to handling routing and page rendering. By leveraging these features effectively, we can create robust and user-friendly web applications.

Comments

Popular posts from this blog

Ultimate Guide to Implementing DELETE Operations in Next.js with Prisma

In this tutorial, we will learn how to delete a post in Next.js using the API and UI code. Deleting a post requires making changes to the folder structure and implementing the delete method. Let's dive in! Changing the Folder Structure Currently, the folder structure for the API is not suitable for deleting posts. We need to pass an ID to delete a specific post. To enable this functionality, we will need to alter the folder structure. Here's how: Create a new folder named "posts" within the API directory. Move the existing file into the "posts" folder. Rename the file to "index". Now, when we access the "posts" endpoint, it will work without specifying the file name. Implementing the Delete Method To delete a post, we need to create a new file in the "posts" folder and pass the I...

Creating API Routes for a Full Stack Application

In this blog post, we will explore how to create API routes for a full stack application. API routes are essential for connecting the frontend components to the backend database and fetching data. We will specifically focus on creating the API routes and endpoints for making API calls and retrieving data. Setting up the Database Before we dive into creating the API routes, we need to set up the database. In this example, we will be using a local PostgreSQL database. To connect to the database, we have a schema file that defines a table called "todos" with four fields: id, name, username, and created_at. Currently, we have two records in the todos table. The next step is to write the API routes to connect to the database and fetch the data. Using Prisma for API Routing To create the API routes, we will be using the Prisma library, specifically the Prisma client. The Prisma client allows us to connect to the database and execute queries. To start with the API rout...

How to use Redux in Next.js

Introduction In this blog post, we will explore how to use Redux with Next.js and create todo and disptach it to Redux store and and pass the todo (state) to a Page and display the created Todo. We will cover the process of setting up the necessary Redux store and cover the end to end flow. Create Next.js application npx create-next-app@latest Install dependencies npm install --save @reduxjs/toolkit npm install --save react-redux npm install --save redux-persist Folders and files needed Create folder lib under src folder(src/lib) Create Interface Todos under lib folder (lib/Todos.ts) export interface ITodo { todosState: [Todo] } export interface Todo { todoName: string, description: string, userName: string, id: string } Create folder store under lib (lib/store) Create fi...