The user wants a "multi-layout system in Next.js that dynamically loads different layouts based on routes."
I need to provide a solution that covers:
- Context: Why is this useful? (Different pages need different headers/footers/sidebars).
- Approaches:
- App Router (Next.js 13+): This is the modern standard. Using Root Layouts and Nested Layouts.
- Pages Router (Legacy/Classic): Using a custom
Layout component and _app.js.
- Core Implementation:
- Define the Layouts (e.g.,
MainLayout, AuthLayout, DashboardLayout).
- Routing structure.
- Mechanism to switch layouts.
Plan for the response:
- Introduction: Briefly explain the concept.
- Approach 1: The Modern App Router (Next.js 13+)
- This is the preferred way now. It relies on file-system based nested layouts.
- Structure:
app/layout.tsx (root), app/(dashboard)/layout.tsx (nested), app/(auth)/layout.tsx (nested).
- Code example for the file structure and the layout files.
- Approach 2: The Pages Router (Classic Next.js)
- Still relevant for many existing projects.
- Mechanism: A HOC (Higher Order Component) or a switch in
_app.tsx.
- Code example showing how to map route paths to components in
_app.tsx.
- Comparison/Recommendation: Briefly suggest App Router for new projects.
Drafting the Content - App Router:
- Folder structure is key here.
- Route Groups
(groupName) are perfect for this. They don't affect the URL path but allow grouping layouts.
- Example:
app/layout.tsx (Root - HTML/Body).
app/(marketing)/layout.tsx (Public pages).
app/(admin)/layout.tsx (Protected pages).
Drafting the Content - Pages Router:
- Needs a custom
MyApp in pages/_app.tsx.
- Need to define a mapping:
{ '/admin': AdminLayout, '/login': AuthLayout }.
- Or, wrap the
Component based on Component.layout static property. That's a cleaner pattern often used in enterprise.
- Decision: I will show the
Component.layout static property approach because it's very flexible, but I'll also mention the route-map approach for simplicity. Let's go with the route-map approach inside _app.js for clarity as it's easier to understand "dynamic loading based on routes" explicitly.
Refining the Prompt Requirements:
"Dynamically loads different layouts based on routes."
Final Structure:
- Prerequisites: Next.js version context.
- Method 1: Using App Router (Next.js 13+) - Highly Recommended.
- Explanation of Route Groups.
- Folder structure visual.
- Code for specific layouts.
- Method 2: Using Pages Router (Next.js 9-12).
- Explanation of
_app.js.
- Code for a custom
getLayout function pattern.
Let's write the code.
Method 1 (App Router):
app/layout.tsx: Basic html/body.
app/(public)/page.tsx: Home.
app/(public)/layout.tsx: Navbar.
app/(admin)/dashboard/page.tsx.
app/(admin)/layout.tsx: Sidebar.
Method 2 (Pages Router):
- Create
layouts/MainLayout.js, layouts/AdminLayout.js.
- In
pages/_app.js:
- Check
router.pathname.
- If starts with
/admin, use AdminLayout.
- Else use
MainLayout.
Alternative Method 2 (Static Property):
pages/about.js: AboutPage.getLayout = (page) => <MainLayout>{page}</MainLayout>
pages/dashboard.js: DashboardPage.getLayout = (page) => <AdminLayout>{page}</AdminLayout>
_app.js: const getLayout = Component.getLayout || ((page) => page)
This is the "Per-Page Layout" pattern from the Next.js docs. I will use this one as it is the most robust way in the Pages router.
Self-Correction during drafting:
The user asked for "dynamically loads... based on routes".
In the App Router, it happens automatically via file structure.
In the Pages Router, the "static property" approach is per-page, but the "route checking" in _app.js is explicitly "based on routes".
I will provide the Route Group method for App Router (best practice) and a Route Matcher method for Pages Router (closest to the literal request).
Step-by-Step Implementation Plan:
- App Router Solution:
- Concept: Route Groups
(folder).
- Implementation: Create
app/(marketing), app/(app) folders.
- Pages Router Solution:
- Concept: Global state/route check in
_app.js.
- Implementation: A
useRouter hook inside _app.js to decide which layout component to render.
Let's stick to the App Router as primary, Pages Router as secondary.
App Router Details:
app/layout.tsx (Root)
app/(auth)/layout.tsx (Centered card)
app/(admin)/layout.tsx (Sidebar)
Pages Router Details:
components/Layouts/MainLayout
components/Layouts/DashboardLayout
pages/_app.js logic to switch.
I will write the response clearly separating these two. I will prioritize the App Router approach as it is the current standard.
Let's write the code snippets.
Layouts: Simple functional components with {children}.
Pages: Simple text.
Wait, for the Pages router, a very clean pattern is Component.getLayout. While technically "per page", it's the idiomatic way to handle layouts. However, if the user specifically wants "based on routes" (e.g. everything under /admin gets the sidebar), doing a check inside _app.js is less repetitive than adding getLayout to every single admin page. I will show a hybrid or the check approach for Pages router.
Let's go with the App Router (Route Groups) approach as the main answer, as it is the modern standard. Then provide the Pages Router approach as a fallback.
App Router Implementation:
app/layout.tsx: Root.
app/(public)/layout.tsx: Header + Footer.
app/(public)/page.tsx: Landing.
app/(admin)/layout.tsx: Sidebar.
app/(admin)/dashboard/page.tsx: Dashboard.
Pages Router Implementation:
layouts/DashboardLayout.js
layouts/PublicLayout.js
pages/_app.js: Logic to detect /admin path.
Okay, ready to generate.
There are two primary ways to handle dynamic layouts in Next.js, depending on which router architecture you are using.
- App Router (Next.js 13+): Uses Route Groups and Nested Layouts (Recommended).
- Pages Router (Legacy): Uses a custom
App component (_app.js) and logic to switch layout components.
Here is a complete guide for both approaches.
Approach 1: App Router (Modern Standard)
Best for: New projects. It uses the file system to handle layout nesting natively.
In the App Router, you use Route Groups. These are folders wrapped in parenthesis (e.g., (admin)). They do not affect the URL path but allow you to isolate layout logic.
1. The File Structure
Create separate folders for your different layout zones (e.g., Marketing vs. Admin).
app/
├── (marketing)/ <-- Group (doesn't affect URL)
│ ├── layout.tsx <-- Layout A (Header/Footer)
│ ├── page.tsx <-- URL: /
│ └── about/
│ └── page.tsx <-- URL: /about
├── (admin)/ <-- Group (doesn't affect URL)
│ ├── layout.tsx <-- Layout B (Sidebar/Dark mode)
│ ├── dashboard/
│ │ └── page.tsx <-- URL: /dashboard
│ └── settings/
│ └── page.tsx <-- URL: /settings
└── layout.tsx <-- Root Layout (Global)
2. Implementation
A. The Root Layout (app/layout.tsx)
This wraps everything. Good for global providers or fonts.
// app/layout.tsx
import './globals.css';
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
B. The Marketing Layout (app/(marketing)/layout.tsx)
This layout automatically applies to the home page and about page.
// app/(marketing)/layout.tsx
import Link from 'next/link';
export default function MarketingLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div className="min-h-screen bg-gray-50">
{/* Marketing Header */}
<header className="bg-blue-600 text-white p-4 flex gap-4">
<Link href="/">Home</Link>
<Link href="/about">About</Link>
<Link href="/dashboard" className="ml-auto">Login to Admin</Link>
</header>
<main className="p-6">
{children}
</main>
<footer className="bg-gray-200 p-4 text-center">
Marketing Footer
</footer>
</div>
);
}
C. The Admin Layout (app/(admin)/layout.tsx)
This layout applies only to dashboard routes.
// app/(admin)/layout.tsx
import Link from 'next/link';
export default function AdminLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div className="flex min-h-screen bg-gray-900 text-white">
{/* Admin Sidebar */}
<aside className="w-64 bg-gray-800 p-6 border-r border-gray-700">
<h2 className="text-xl font-bold mb-6">Admin Panel</h2>
<nav className="flex flex-col gap-2">
<Link href="/dashboard" className="hover:text-blue-400">Dashboard</Link>
<Link href="/settings" className="hover:text-blue-400">Settings</Link>
<Link href="/" className="text-gray-400 text-sm mt-10">Back to Site</Link>
</nav>
</aside>
<section className="flex-1 p-8">
{children}
</section>
</div>
);
}
Approach 2: Pages Router (Legacy / Classic)
Best for: Existing projects not ready to migrate to the App Router.
In the Pages router, you must handle the logic manually in _app.tsx. We use a pattern called "Per-Page Layouts".
1. Define Layout Components
Create your layout components in a components folder.
// components/MainLayout.tsx
export const MainLayout = ({ children }) => (
<div className="bg-white p-10 border-b-4 border-blue-500">
<h1>Standard Site Layout</h1>
{children}
</div>
);
// components/AdminLayout.tsx
export const AdminLayout = ({ children }) => (
<div className="bg-gray-900 text-white p-10 border-b-4 border-red-500">
<h1>Admin Dashboard Layout</h1>
{children}
</div>
);
2. Configure _app.tsx
We check if the component being loaded has a static layout property attached to it.
// pages/_app.tsx
import type { ReactElement, ReactNode } from 'react';
import type { NextPage } from 'next';
import type { AppProps } from 'next/app';
import { MainLayout } from '../components/MainLayout';
import { AdminLayout } from '../components/AdminLayout';
// 1. Define a type for NextPage with an optional getLayout function
type NextPageWithLayout = NextPage & {
getLayout?: (page: ReactElement) => ReactNode;
};
type AppPropsWithLayout = AppProps & {
Component: NextPageWithLayout;
};
export default function MyApp({ Component, pageProps }: AppPropsWithLayout) {
// 2. If the page has a custom layout defined, use it.
// Otherwise, fallback to the default 'MainLayout'.
const getLayout = Component.getLayout ?? ((page) => <MainLayout>{page}</MainLayout>);
return getLayout(<Component {...pageProps} />);
}
3. Assign Layouts to Pages
Now, inside your page files, you export a static function called getLayout.
Regular Page (pages/index.tsx)
Uses the default layout automatically.
// pages/index.tsx
export default function HomePage() {
return <div>Welcome to the Public Site</div>;
}
Admin Page (pages/dashboard.tsx)
Overrides the layout.
// pages/dashboard.tsx
import { AdminLayout } from '../components/AdminLayout';
export default function DashboardPage() {
return <div>Secret Dashboard Data</div>;
}
// Define the layout for this specific page
DashboardPage.getLayout = function getLayout(page) {
return <AdminLayout>{page}</AdminLayout>;
};
Summary of Differences
| Feature | App Router (Route Groups) | Pages Router (getLayout) |
|---|
| Logic Location | File System (Folder structure) | JavaScript Code (_app.tsx) |
| State Preservation | Native (Layouts persist) | Manual (Require careful memoization) |
| Setup Complexity | Low (Just folders) | Medium (TypeScript types needed) |
| Performance | Highly optimized (Server Components) | Standard React rendering |
If you are starting a new project, use Approach 1 (App Router).