Horje
Next.js Route Groups and Project Organization

Next.js Route Groups allow you to logically group and organize routes within your Next.js application. This is particularly useful for large projects, making the codebase easier to navigate and manage.

How Do Route Groups Work?

Route Groups are created by structuring files and directories within the pages or app directory (depending on whether you’re using the pages router or the app router introduced in Next.js 13). Each file in these directories corresponds to a route in your application.

Different ways to use Route Groups in the Next.js app

1. Without URL impact

The given example is the best use case for organizing the pages without impacting the URL using route groups. This can be achieved using a set of open and closed parenthesis around the auth folder.

Screenshot-2024-07-18-171909

Route groups

2 Route Groups for Layouts

Layouts are the set of UI designed that a application follow to maintain the consistency of the user interface across the website. For example, we can provide same layout design for authentication pages like login, sign up and forgot password pages. Instead of creating a layout design with code duplicates, we can create a single layout and assign that layout to all the pages present in the layout route group.

Screenshot-2024-07-18-171445

Route groups for layouts

3. Creating multiple root layouts

Next.js allows the users to create multiple root layouts using Route Groups. This is used to completely style different UIs for different parts of the web app. For example, we can define a different UI for the landing page which may have home and about section which follows the landing page UI. Similarly, we can completely define different UI for authorization section which contains login, sign up pages that follows same UI that are different from Landing page UI. This method provides the UI independency.

Screenshot-2024-07-19-162853

Root Layout

In this above example, the default route is /landingPage and the pages inside the landing page i.e, /home and /about page also follows the landingPage-layout. Similarly for the /auth routes follow auth-layout also. This method is used to custom the UI for each route groups.

Steps to Implement Route Groups

Step 1: Create a new project

Open the terminal and provide the below command to create a new Next.js app.

npx create-next-app@latest my-app

Step 2: Install the necessary dependencies

If it prompts anything, kindly choose yes. Provide the following details in the image. This will install the necessary dependencies for the project.

Screenshot-2024-07-08-163148

Provide the following details

Features

Let’s analyze the next app structure and its features:

Src Directory

This is a main directory in Next.js app where all the codes, pages, routes, hooks, states will be present. If a user provides any function outside of this src directory, then it will be difficult to navigate to the file, takes too long to render and not suitable for small scale projects. Similar to the src directory, the public directory is used to store the static files such as images, GIFs and other multi media contents.

Route Group

Route groups are a special feature of Next.js that are used to keep the same functioning routes inside a single folder and prevent the nested folder in URL path.

Benefits

  • Organizing routes into groups
  • Enabling nested layouts in the same route segment level
  • Enable a layout to a subset of routes in a common segment

Private Folder

Private folder contains the sensitive data files that are not allowed to be modified manually. In Next.js, .next that is present in the root folder is considered to be the private folder that contains the details of the server, cache and others.

Screenshot-2024-07-19-212112

Private Folder

Module Path Aliases

This feature in Next.js allows developers to config the aliases for simplifying the imports. This can be done in next.config.mjs file present in the root directory. For example, if we want to import the images folder from the public/images directory we can config like below:

// next.config.mjs
module.exports = {
  webpack: (config, { isServer }) => {
    config.resolve.alias = {
      '@images': './public/images',
      // ... other aliases
    };
    return config;
  },
};

Strategies to store the project files

There are several ways to structure the Next.js project files. Some of them are:

Store project files outside of app

Placing the project files outside the src/app folder will enable to share the code across multiple apps. This strategy is useful in large scale productions where there is a need to reuse the component/ functions across different applications.

Store project files in top-level folders inside of the app

This strategy allows the developers to store the reusable components, styles and other properties in the same directory. For example, we can use components, styles and pages directories to store different reusable components, styles and pages.

Screenshot-2024-07-19-215440

store project files in top-level folders inside of app

Split project files by feature or route

This strategy enable developers to split and store the files of same category in the same directory. For example, we can split the authentication process, contacts process as a separate directory and use route groups on the directory.

Edit the contents of the app

Navigate to the app folder which is present inside the src folder. Delete all the contents present in the app folder and create a new typescript file page.tsx . This will act as a default page. Check the below image for reference

Screenshot-2024-07-08-164951

Home Page

Provide the following content to the home page.

import React from 'react';

function page() {
    return (
        <h1>Home Page</h1>
  )
}

export default page;

Similarly, create three folders named: login, signup and forgot-password with page.tsx in each folder. By creating these folders will create a routing for each page i.e, /login, /signup and /forgot-password. The result should look like the below image.

Screenshot-2024-07-08-165727

After page creations

Note: Each folder should contain page.tsx, since Next.js follows the files and folder configuration for routing, whenever there is a new folder created inside the app folder a route is created with the name of the folder. Ensure to add some content to each page.tsx.

Route the app using Route groups

Since the login, signup and forgot password pages are related to authentication and authorization purposes, we can place these three pages inside a common folder auth.

Screenshot-2024-07-08-171332

Reference

This will create a route similar to this: ‘localhost:3000/auth/login’. To avoid the auth in between the routed url, we can use route groups. Include the open and close parenthesis around auth to config the route groups.This will avoid the extra auth in between the url.

Screenshot-2024-07-08-172758

Layout Route group

We can also add common layout for the auth folder using the same method as route groups but we will create layout.jsx file.

Screenshot-2024-07-08-174733

The folders should look like this

The layout.tsx must look like:

export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}

export default function AuthLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div>
<h2>Layout</h2>
<body>{children}</body>
</div>
)
}

Output




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
Next.js Exercises, Practice Questions and Solutions Next.js Exercises, Practice Questions and Solutions
Explain the Benefits and Challenges of Using WebSockets in Redux Applications. Explain the Benefits and Challenges of Using WebSockets in Redux Applications.
Methods to Optimize the re-render in React-Redux Connected Component? Methods to Optimize the re-render in React-Redux Connected Component?
How React Works? How React Works?
Explain The Benefits And Challenges Of Caching And Offline Support in Redux Explain The Benefits And Challenges Of Caching And Offline Support in Redux

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
24