Skip to main content

Software Development

Routing in Next.js: Unraveling File-Based, Dynamic, Route Groups, and Layouts

Two people working on a laptop in a warehouse

What is Routing?

The Pages Router utilizes a file-system-based routing system grounded in the concept of pages. Upon adding a file to the app directory, it becomes readily accessible as a route.

File Based Routing:

Each component in the app directory automatically becomes a route in your application.

Img 16

If you have a file named page.js inside the about folder within the app directory, it would be accessible at the /about route.

Path: src/app/about/page.js

export default function About() {
    return <h1>About</h1>
}

Output:

Img 29

Path: src/app/profile/page.js

export default function Profile() {
    return <h1>Profile</h1>
}

Output:

Img 28

What are Dynamic Routes?

Dynamic routes in Next.js let you create web pages with variable parts in the URL. Using brackets ‘[]’, you can define these dynamic segments, allowing your pages to adapt to different inputs or parameters, making your application more versatile.

Folder Structure:

Img 20

  • I am retrieving the product list data using client-side fetching.
  • Dynamic routing in Next.js allows you to create pages with dynamic parameters. In this case, the parameter is item.id.
  • The <Link> component from Next.js is used for client-side navigation. When a user clicks on a product title, they will be taken to the dynamically generated product page.

Path: src/app/productlist/page.js

"use client"
import Link from 'next/link'
import { useState, useEffect } from 'react';

const ProductList = () => {

    const [product, setProduct] = useState([]);

    useEffect(() => {
        getAsync();
    }, []);

    const getAsync = async () => {
        let data = await fetch("https://dummyjson.com/products")
        data = await data.json();
        console.log(data);
        setProduct(data.products);
    };

    return (
        <>
            <h1>Product List</h1>
            <ul>
                {product.map((item) => (
                    <li key={item.id}>
                        <Link href={`/productlist/${item.id}`}>
                            {item.title}
                        </Link>
                       
                    </li>
                ))}
            </ul>
        </>

    );
}
export default ProductList;

Path: src/app/productlist/[Id]/page.js

import React from 'react'
const page = () => {
  return (
    <>
      <h3>As you can see the URL is dynamically changing</h3>
    </>
  )
}

export default page

Output:

Img 23

  • When you click on a title, it takes you to a special page about that title.
  • The link is unique for each title, so if you click on the first title, it goes to a page with ID 1, and for the second title, it goes to a page with ID 2.
  • This is done smoothly using Next.js dynamic routing, which helps the website adjust to different titles without much hassle.

Output:

Img 24                                                                           Img 25

Let’s Understand Routes Group

First, we’ll grasp the fundamental structure of Next.js, and then we’ll delve into the concepts of route groups.

Folder Structure:

Img 1

If you look at my folder setup, it goes like this: Auth/LoggedIn/SignOut/SignUp in Next.js. So, to get to different pages, you’d find “LoggedIn” under “Auth/LoggedIn,” “SignOut” at “Auth/SignOut,” and “SignUp” at “Auth/SignUp.”

Img 34

What is Route Group?

Ever noticed how folders on your computer neatly organize files? Websites work similarly, but what users see in a website’s address isn’t always what’s behind the scenes. Enter Route Groups in Next.js, the magic that tidies up a website’s address without changing its structure!

Route Groups: Keeping Your Web Address Tidy

  • Typically, website folders match parts of the site’s address. But with Route Groups, you have control. You can decide which folders stay hidden from the website’s address while keeping your project organized behind the scenes.
  • For instance, imagine a folder called “Auth” with login-related stuff inside. By using Route Groups, you can access pages like “LoggedIn,” “SignOut,” or “SignUp” directly without displaying the whole folder structure in the URL. It’s like having a secret passage to specific pages, making the website’s address cleaner and easier for users.
  • This means that by placing the main folder, “Auth,” within parentheses, it becomes hidden in the URL structure. As a result, you can access the URL without having to include or display the “Auth” folder in the path.

Img 3

Path: src/app/Auth/LoggedIn/page.js

const LogIn = () => {
   return(
    <h1>LoggedIn Page</h1>
   )
}
export default LogIn;

Output:

Img 30

Path: src/app/Auth/SignOut/page.js

const SignOut = () => {
    return(
        <h1>SignOut Page</h1>
    )
}
export default SignOut

Output:
Img 31

Path: src/app/Auth/SignUp/page.js

const SignUp = () => {
    return(
        <h1>SignUp Page</h1>
    )
}
export default SignUp

Output:

Img 32

  • With Route Groups in Next.js, you have the flexibility to access the “LoggedIn” page directly without showing the entire folder structure in the website’s address. So, instead of having to go through “Auth/LoggedIn” in the folder structure to reach the page, you can set it up so that users access the “LoggedIn” page simply by typing its designated path, making the URL cleaner and more straightforward for users.
  • This doesn’t change how your folders are organized internally; it just affects what users see in their browser’s address bar.
  • Similarly, you can access the “SignOut” and “SignUp” pages without needing to include the “auth” folder in the path.

What is Root Layout?

  • A root layout in Next.js is like a frame that surrounds everything on your website. It sets up basic things for all pages, like the language and styles.
  • In simpler words, the code you provided creates a base structure (the RootLayout) that wraps around all the content on your website. This structure sets basic settings and styles for every page, such as the website’s language (like English) and a specific font style for the text.
  • The metadata section holds important info about the webpage, such as its title and description, which are used by search engines and browsers.
  • Basically, the Root Layout function helps keep the look and behavior consistent across all the pages of your Next.js website.

Path: src/app.layout.js

import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })
export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}
// export default function RootLayout({ children, sidebar, main }) {
export default function RootLayout({ children }) {
  const boolean = true;
  return (
    <html lang="en">
      <body className={inter.className}>
          {children}
      </body>
    </html>
  )
}

What is Layout?

  • When you visit different pages on a website, you expect them to look similar, right? Like having the same top bar or menu. Well, in Next.js (a way to build websites), there’s this thing called a “layout.”
  • A layout is like a plan that says how all the pages should look. It’s super handy because instead of copying the same design for every page, you create a layout with things like headers, footers, and menus that you want on every page.
  • For example, think about a folder for logging into a website. Inside that folder, there might be a special file called “layout.js.” This file acts as the boss, deciding how all the login pages will look.

Folder structure:

Img 7

  • Now, in that login folder, you might find separate folders for things like “LoginStudent” and “LoginTeacher.” Each of these folders has pages for those specific actions.
  • That “layout.js” file is crucial because it sets the rules for how all these pages in the login section will appear. It makes sure they all have the same style, like the same header or menu, to make things smooth and consistent.

Path: src/app/Login/layout.js

"use client"
import Link from "next/link";
import './Style/Login.css'
import { usePathname } from "next/navigation";
const Layout = ({ children }) => {
    const pathName = usePathname()
    console.log(pathName);
    return (
        <>
                <ul className="login-nav">
                    <li><h4>Login Navbar</h4></li>
                    <li><Link href="/Login">Login Page</Link></li>
                    <li><Link href="/Login/LoginStudent">Login Student Page</Link></li>
                    <li><Link href="/Login/LoginTeacher">Login Teacher Page</Link></li>
                </ul> 
            {children}

        </>
    )
}
export default Layout

Path: src/app/Login/page.js

import Link from "next/link";
const page = () => {
  return (
    <div>
      <h3>login Page</h3>
      <Link href="/">Go to Home Page</Link>
    </div>
  )
}

export default page

Output:

Img 11

Path: src/app/Login/LoginStudent/page.js

"use client"
import { useRouter } from "next/navigation"
const page = () => {
    const router = useRouter();
    const navigate = (name) => {
        router.push("/Login" + name);
    }
    return (
        <div>
            <h3>Login Student Page</h3>
            <button onClick={() => 
                  navigate ("/LoginTeacher")}>
                Go to Login Teacher Page</button>
        </div>
    )
}

export default page

Output:

Img 12

Path: src/app/Login/LoginTeacher/page.js

const page = ()=> {
  return (
    <div>
      <h3>Login Teacher Page</h3>
    </div>
  )
}

export default page

Output:

Img 13

 

  • By using layouts like this, website makers can make sure that no matter which login-related page you’re on, they all feel and look alike. It’s like giving each page a similar vibe, making it easier for you to navigate and use the site.
  • In simple words, layouts in Next.js are like the captains that ensure all the pages in one section of a website have the same look and feel.

If I open the “About” page, the navbar from “layout.js” won’t appear there. Since it’s made for the Login Folder, it only shows up on pages directly connected to it.

Path: src/app/about/page.js

const page = ()=> {
    return (
      <div>
        <h1>About Page</h1>
      </div>
    )
  }
  export default page

Output:

Img 29

Conclusion:

The blog concludes that understanding Next.js routing concepts, including file-based routing, dynamic routes, route groups, root layouts, and layouts, is crucial for creating clean, organized, and user-friendly websites. Practical examples illustrate the impact of these concepts on URL structure, consistency, and navigation.

Thoughts on “Routing in Next.js: Unraveling File-Based, Dynamic, Route Groups, and Layouts”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Anam Firdous

Anam Firdous, an associate technical consultant at Perficient, excels in front-end development, particularly in Sitecore, and holds expertise in SCORE. Her focus lies in crafting top-notch web solutions across diverse industries by leveraging various front-end technologies, showcasing her prowess in UI development.

More from this Author

Follow Us