Next.js course Β· Module 2: Routing and Layouts
Route Grouping and Organization
In this lesson6
At the heart of the Quantum Metropolis, the urban space management system is based on the concept of thematic districts and functional zones. The city is divided into recognizable areas - a science district, residential zone, entertainment district, and many others. These zones are separated from each other but work together as elements of a single, cohesive urban organism.
Similarly, in Next.js 16, we can organize and group routes in our application to increase code clarity, improve management, and enable more flexible loading strategies and component isolation.
Route Groups
In App Router, we can create route groups that have no impact on the actual URL structure by placing a directory in parentheses, for example: (groupName). This is a powerful feature that allows for logical code organization without changing its behavior or public API.
Route Group Structure and Syntax
Route groups are defined by placing the directory name in parentheses:
app/
βββ (marketing)/ # Group for marketing pages
β βββ about/
β β βββ page.tsx # /about
β βββ blog/
β β βββ page.tsx # /blog
β βββ layout.tsx # Shared layout for marketing pages
β
βββ (shop)/ # Group for marketing pages
β βββ products/
β β βββ page.tsx # /products
β βββ cart/
β β βββ page.tsx # /cart
β βββ layout.tsx # Shared layout for shop pages
β
βββ layout.tsx # Main application layoutIn this example, the /about and /blog routes are part of the (marketing) group, while /products and /cart are part of the (shop) group. Note that route groups do not affect the actual URLs - the (marketing) directory is not part of the /about URL path.
Route Group Applications
1. File and Folder Organization
The simplest use of route groups is logical file organization, especially in larger applications:
app/
βββ (main)/ # Main public pages
β βββ page.tsx # Home (/)
β βββ about/ # /about
β βββ contact/ # /contact
β
βββ (auth)/ # Authentication-related pages
β βββ login/ # /login
β βββ register/ # /register
β βββ forgot-password/ # /forgot-password
β
βββ (dashboard)/ # Dashboard pages (protected)
β βββ account/ # /account
β βββ settings/ # /settings
β βββ billing/ # /billing
β
βββ layout.tsx # Main layout2. Sharing Layouts Between Specific Routes
One of the most powerful uses of route groups is the ability to define shared layouts for specific groups of pages without affecting the URL paths:
// app/(marketing)/layout.tsx - Layout for marketing pages
export default function MarketingLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="marketing-layout">
<nav className="marketing-nav">
<a href="/about">About Us</a>
<a href="/blog">Blog</a>
<a href="/careers">Careers</a>
</nav>
<main>{children}</main>
<footer className="marketing-footer">
<p>Β© 2150 Quantum Voyages. All rights reserved.</p>
</footer>
</div>
);
}// app/(shop)/layout.tsx - Layout for shop pages
export default function ShopLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="shop-layout">
<header className="shop-header">
<h1>Quantum Voyages Store</h1>
<nav className="shop-nav">
<a href="/products">Products</a>
<a href="/categories">Categories</a>
<a href="/cart">Cart</a>
</nav>
</header>
<main>{children}</main>
<aside className="shop-sidebar">
<div className="popular-products">
<h3>Popular Products</h3>
{/* List of popular products */}
</div>
</aside>
</div>
);
}3. Splitting the Application into Sections
Route groups are particularly useful in multi-section applications, such as an application with a public homepage, admin panel, and user dashboard:
app/
βββ (public)/ # Public part of the website
β βββ page.tsx # Home (/)
β βββ about/ # /about
β βββ blog/ # /blog
β β βββ [slug]/ # /blog/:slug
β βββ layout.tsx # Public layout
β
βββ (admin)/ # Admin panel
β βββ admin/ # /admin (note: the admin/ directory is needed to preserve the URL)
β β βββ page.tsx # /admin
β β βββ users/ # /admin/users
β β βββ settings/ # /admin/settings
β βββ layout.tsx # Admin layout
β
βββ (dashboard)/ # User dashboard
β βββ dashboard/ # /dashboard
β β βββ page.tsx # /dashboard
β β βββ profile/ # /dashboard/profile
β β βββ settings/ # /dashboard/settings
β βββ layout.tsx # Dashboard layout
β
βββ layout.tsx # Main layout (shared across all sections)In this example, the application is divided into three main sections, each with its own layout, but all sharing a common main layout.
Quantum Voyages Example
Let's implement a route group system for our space application Quantum Voyages:
app/
βββ (marketing)/ # Marketing pages
β βββ page.tsx # Home (/)
β βββ about/ # /about
β βββ destinations/ # /destinations
β β βββ [id]/ # /destinations/:id
β βββ layout.tsx # Marketing layout
β
βββ (customer)/ # Pages for logged-in customers
β βββ dashboard/ # /dashboard
β βββ bookings/ # /bookings
β β βββ [id]/ # /bookings/:id
β βββ account/ # /account
β βββ layout.tsx # Customer layout
β
βββ (admin)/ # Admin panel
β βββ admin/ # /admin
β β βββ voyages/ # /admin/voyages
β β βββ customers/ # /admin/customers
β β βββ analytics/ # /admin/analytics
β βββ layout.tsx # Admin layoutistracyjny
β
βββ layout.tsx # Main layoutCode for the layouts:
// app/layout.tsx - Main layout
import { Inter } from 'next/font/google';
import './globals.css';
const inter = Inter({ subsets: ['latin'] });
export const metadata = {
title: 'Quantum Voyages - Space Travels from the Quantum Metropolis',
description: 'Discover space with the Quantum Metropolis guide',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="pl">
<body className={inter.className}>
{children}
</body>
</html>
);
}// app/(marketing)/layout.tsx - Marketing layout
import Header from '@/components/marketing/Header';
import Footer from '@/components/marketing/Footer';
export default function MarketingLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<>
<Header />
<main className="min-h-screen pt-16 pb-20">
{children}
</main>
<Footer />
</>
);
}// app/(customer)/layout.tsx - Layout for logged-in customers
import CustomerHeader from '@/components/customer/Header';
import CustomerSidebar from '@/components/customer/Sidebar';
import { checkAuth } from '@/lib/auth';
import { redirect } from 'next/navigation';
export default async function CustomerLayout({
children,
}: {
children: React.ReactNode;
}) {
// Check if the user is logged in
const user = await checkAuth();
if (!user) {
// The layout is a Server Component: there is no window object here. proxy.ts can add the return address.
redirect('/login');
}
return (
<>
<CustomerHeader user={user} />
<div className="flex min-h-screen pt-16">
<CustomerSidebar />
<main className="flex-1 p-6 bg-gray-50">
{children}
</main>
</div>
</>
);
}// app/(admin)/layout.tsx - Admin layout
import AdminHeader from '@/components/admin/Header';
import AdminSidebar from '@/components/admin/Sidebar';
import { checkAdminAuth } from '@/lib/auth';
import { redirect } from 'next/navigation';
export default async function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
// Check if the user is an admin
const isAdmin = await checkAdminAuth();
if (!isAdmin) {
redirect('/admin-login');
}
return (
<div className="admin-layout">
<AdminHeader />
<div className="flex min-h-screen pt-16">
<AdminSidebar />
<main className="flex-1 p-6 bg-gray-100">
{children}
</main>
</div>
</div>
);
}Groups Only for Organizing Files
A route group doesn't need its own layout.tsx. You can use it only to keep files in order, and the URLs stay the same:
app/
βββ (onboarding)/welcome/
β βββ page.tsx # /welcome
βββ (payments)/cart/
βββ page.tsx # /cartSeparating Layouts and URL Paths
Route groups are particularly useful when we want to share a layout between specific routes that aren't necessarily close to each other in the URL hierarchy:
app/
βββ (auth)/
β βββ login/ # /login
β β βββ page.tsx
β βββ register/ # /register
β β βββ page.tsx
β βββ layout.tsx # Shared layout only for /login and /register
β
βββ account/ # /account (does not use the (auth) layout)
β βββ page.tsx
β
βββ layout.tsx # Main layout for all routesPrivate Folders (_folderName)
Next.js 16 also supports the private folders convention, which are marked with an underscore (_) at the beginning of the name. Such folders are not included in URL paths but can contain code shared by multiple routes.
Private Folder Structure and Syntax
app/
βββ _components/ # Private folder for shared components
β βββ Button.tsx # Button component
β βββ Card.tsx # Card component
β βββ SearchForm.tsx # Search form component
β
βββ _lib/ # Private folder for shared functions
β βββ api.ts # API functions
β βββ utils.ts # Utility functions
β
βββ destinations/ # Public route
β βββ page.tsx # /destinations
β
βββ page.tsx # Home (/)In this example, the _components and _lib directories are private and do not generate any URL paths. They are used to store shared components and functions that can be imported by other components.
Difference Between Private Folders and Route Groups
Private folders and route groups look similar but have different use cases:
- Private folders (
_folderName) are used to organize code that should not be directly accessible via URL. - Route groups (
(folderName)) are used to group routes without affecting URL paths, but they can influence layout behavior.
Example of Using Private Folders in the Quantum Voyages Application
app/
βββ _components/ # Shared UI components
β βββ ui/ # Basic UI components
β β βββ Button.tsx
β β βββ Card.tsx
β β βββ Input.tsx
β β
β βββ marketing/ # Components for marketing pages
β β βββ HeroSection.tsx
β β βββ TestimonialCard.tsx
β β
β βββ bookings/ # Components for the booking system
β βββ BookingForm.tsx
β βββ PlanetSelector.tsx
β
βββ _lib/ # Shared functions and utilities
β βββ api/ # Functions for API communication
β β βββ destinations.ts
β β βββ bookings.ts
β β
β βββ hooks/ # Custom React hooks
β β βββ useBooking.ts
β β βββ useAuth.ts
β β
β βββ utils/ # Helper functions
β βββ dates.ts
β βββ validation.ts
β
βββ _data/ # Static data (you can also use /public)
β βββ destinations.json
β βββ testimonials.json
β
βββ (marketing)/ # Group for marketing pages
β βββ page.tsx # Home (/)
β βββ about/ # /about
β βββ destinations/ # /destinations
β
βββ (customer)/ # Group for customer pages
βββ dashboard/ # /dashboard
βββ bookings/ # /bookingsExample code using private folders:
// app/_components/ui/Button.tsx
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/app/_lib/utils/cn';
const buttonVariants = cva(
'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-10 px-4 py-2',
sm: 'h-9 rounded-md px-3',
lg: 'h-11 rounded-md px-8',
icon: 'h-10 w-10',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
export function Button({
className,
variant,
size,
asChild = false,
...props
}: ButtonProps) {
return (
<button
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}// app/(marketing)/destinations/page.tsx
import { getDestinations } from '@/app/_lib/api/destinations';
import DestinationCard from '@/app/_components/marketing/DestinationCard';
import { HeroSection } from '@/app/_components/marketing/HeroSection';
export default async function DestinationsPage() {
const destinations = await getDestinations();
return (
<div className="container mx-auto px-4 py-12">
<HeroSection
title="Discover Space with Quantum Voyages"
subtitle="Browse our space destinations and plan your adventure"
image="/images/space-banner.jpg"
/>
<section className="my-12">
<h2 className="text-3xl font-bold mb-8">Popular Destinations</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{destinations.map((destination) => (
<DestinationCard
key={destination.id}
destination={destination}
/>
))}
</div>
</section>
</div>
);
}Route Files (route.js)
Next.js 16 enables creating API endpoints using route.js (or route.ts) files. These files can also benefit from organizational techniques such as route groups and private folders.
API Endpoint Organization
app/
βββ api/ # Main API section
β βββ (public)/ # Public endpoints
β β βββ destinations/
β β β βββ route.ts # GET /api/destinations
β β βββ newsletter/
β β βββ route.ts # POST /api/newsletter
β β
β βββ (protected)/ # Protected endpoints (require authorization)
β β βββ bookings/
β β β βββ route.ts # GET, POST /api/bookings
β β β βββ [id]/
β β β βββ route.ts # GET, PUT, DELETE /api/bookings/:id
β β βββ user/
β β βββ route.ts # GET /api/user
β β
β βββ _middleware/ # Middleware for API (private folder)
β βββ auth.ts # Authentication middleware
β βββ rateLimit.ts # Rate limiting middleware
β
βββ page.tsx # Home (/)Example implementation of a protected API endpoint:
// app/api/(protected)/bookings/route.ts
import { NextResponse } from 'next/server';
import { verifyAuth } from '@/app/api/_middleware/auth';
import { rateLimit } from '@/app/api/_middleware/rateLimit';
export async function GET(request: Request) {
// Verify authentication
const authResult = await verifyAuth(request);
if (!authResult.isAuthenticated) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Rate limiting
const rateLimitResult = await rateLimit(request);
if (!rateLimitResult.success) {
return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
}
// Get bookings for the logged-in user
const userId = authResult.user.id;
const bookings = await getBookingsForUser(userId);
return NextResponse.json({ bookings });
}
export async function POST(request: Request) {
// Verify authentication
const authResult = await verifyAuth(request);
if (!authResult.isAuthenticated) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Parse data from the request
const data = await request.json();
// Data validation
const validationResult = validateBookingData(data);
if (!validationResult.success) {
return NextResponse.json({ error: validationResult.errors }, { status: 400 });
}
// Create booking
const userId = authResult.user.id;
const booking = await createBooking(userId, data);
return NextResponse.json({ booking }, { status: 201 });
}Best Practices for Route Organization in Large Applications
In the Quantum Metropolis, detailed planning is key to the efficient functioning of the city. Similarly, in larger Next.js 16 applications, it's important to follow specific rules and patterns for route organization:
1. Use a Clear and Consistent Structure
Maintain a consistent directory structure and naming throughout the application:
app/
βββ (sections)/ # Groups for main sections
β βββ (marketing)/ # Public section
β βββ (app)/ # Main application
β βββ (admin)/ # Admin panel
β
βββ _lib/ # Shared code
β βββ components/ # Shared components
β βββ hooks/ # React hooks
β βββ utils/ # Utility functions
β
βββ api/ # API endpoints
β βββ (public)/
β βββ (protected)/
β
βββ layout.tsx # Main layout2. Share Components Wisely
Use private folders to store shared components and place them at the appropriate hierarchy level:
- Components used throughout the application:
app/_components/ - Section-specific components:
app/(section)/_components/
3. Apply Separation of Concerns
page.js- Page rendering and data fetchinglayout.js- UI layout and navigation logicloading.js- Loading stateserror.js- Error handlingnot-found.js- Missing resource handling
4. Use Import Aliases in tsconfig.json/jsconfig.json
Configure import aliases to simplify paths:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./*"],
"@components/*": ["./app/_components/*"],
"@lib/*": ["./app/_lib/*"],
"@hooks/*": ["./app/_lib/hooks/*"],
"@utils/*": ["./app/_lib/utils/*"]
}
}
}This allows you to import components in a more readable way:
// Instead of:
import { Button } from '../../../_components/ui/Button';
// You can use:
import { Button } from '@components/ui/Button';5. Implementation for the Quantum Voyages Application
Example of a comprehensive structure for a large Quantum Voyages application:
app/
βββ (public)/ # Public part of the website
β βββ _components/ # Components specific to the public section
β βββ page.tsx # Home (/)
β βββ about/ # /about
β βββ destinations/ # /destinations
β β βββ page.tsx # Destination list
β β βββ [id]/ # /destinations/:id
β β βββ page.tsx # Destination details
β βββ contact/ # /contact
β βββ layout.tsx # Public layout
β
βββ (auth)/ # Authentication section
β βββ _components/ # Authentication components
β βββ _lib/ # Authentication logic
β βββ login/ # /login
β βββ register/ # /register
β βββ forgot-password/ # /forgot-password
β βββ layout.tsx # Authentication layout
β
βββ (app)/ # Main application (for logged-in users)
β βββ _components/ # Application components
β βββ dashboard/ # /dashboard
β βββ bookings/ # /bookings
β β βββ page.tsx # Booking list
β β βββ new/ # /bookings/new
β β βββ [id]/ # /bookings/:id
β β βββ page.tsx # Booking details
β β βββ edit/ # /bookings/:id/edit
β βββ account/ # /account
β β βββ page.tsx # Account overview
β β βββ profile/ # /account/profile
β β βββ preferences/ # /account/preferences
β βββ layout.tsx # Application layout
β
βββ (admin)/ # Admin panel
β βββ _components/ # Admin components
β βββ admin/ # /admin (folder needed for the URL)
β β βββ page.tsx # Admin dashboard
β β βββ users/ # /admin/users
β β βββ destinations/ # /admin/destinations
β β βββ bookings/ # /admin/bookings
β βββ layout.tsx # Admin layouta
β
βββ _components/ # Shared components
β βββ ui/ # Basic UI components
β βββ forms/ # Form components
β
βββ _lib/ # Shared functions
β βββ api/ # API functions
β βββ hooks/ # Custom hooks
β βββ utils/ # Utility functions
β
βββ api/ # API endpoints
β βββ (public)/ # Public API
β βββ (protected)/ # Protected API
β
βββ layout.tsx # Main layoutSummary
Route grouping and organization in Next.js 16 offers many possibilities for structuring applications in a logical and clear way, similar to how urban zoning in the Quantum Metropolis organizes urban space for maximum efficiency and functionality.
Key concepts:
Route groups (
(groupName)) - allow logical grouping of routes without affecting URL paths, which is particularly useful for dividing different application sections and implementing specific layouts.Private folders (
_folderName) - enable organization of code, shared components, and functions that are not directly accessible via URL.Hierarchical layouts - the ability to define specific layouts for different route groups, ensuring a consistent user experience within each section.
API organization - applying the same organizational principles to API endpoints.
With these techniques, you can create applications that are:
- More transparent and easier to maintain
- Flexible in terms of navigation and user experience
- Well-organized for development teams
- Scalable for growing applications
In the next chapter, we'll discover how to handle more complex navigation scenarios, such as nested routes and catch-all parameters, which enable creating advanced and flexible navigation systems in Next.js 16 applications.
Docs entries used in this lesson
Spotted a mistake in this lesson?