Build a multi-layout system in Next.js that dynamically loads different layouts based on…
- User
Build a multi-layout system in Next.js that dynamically loads different layouts based on routes.
- Assistant
Considering multi-layout systems
The user wants to build a multi-layout system in Next.js that loads different layouts based on routes. They likely want guidance, code, and explanations. Given that the Next.js version isn’t specified, I'll offer solutions for both versions: using the app router or the pages router, maybe choosing the latest, Next 14.
I'll provide both options: the app router with nested layouts and the pages router with a per-page
getLayoutpattern. I'll include code examples and dynamic imports, too!Outlining dynamic layout importsThe user might want to incorporate dynamic imports for layout components based on routes to aid in code splitting. For example, I could use
const AdminLayout = dynamic(() => import('../components/layouts/AdminLayout'), { ssr: false }).But since Next.js does code splitting per page, a normal import can work too. They mentioned dynamically loading layouts based on routes, so I'd show how to map routes to layout components.
I need to clarify which router they're using: App Router (Next 13+) or the classic Pages Router, so I’ll provide separate sections for each. I'll focus on practical solutions and provide step-by-step guidance!Illustrating dynamic layout folder structure
I want to explain the folder structure for implementing a multi-layout system in Next.js:
For an example, it could look like this:
app/ (public)/ layout.tsx // PublicLayout page.tsx about/page.tsx (dashboard)/ layout.tsx // DashboardLayout page.tsx settings/page.tsxI would define
PublicLayoutandDashboardLayoutfunctions. Each route group would have its layout code-split, so I could suggest dynamic imports for heavier components.For the Pages Router, I would introduce the per-page
getLayoutpattern, including detailed steps to implement it and a layout component map based on specific route patterns.Implementing dynamic layouts in Next.jsTo dynamically load a layout based on the current route, I could start with something like this:
const { Layout } = layoutsMap.find(({ pattern }) => pattern.test(router.pathname)) ?? { Layout: MainLayout }; return ( <Layout> <Component {...pageProps} /> </Layout> );I would also show how to use a dynamic import for each layout, like so:
const AdminLayout = dynamic(() => import('../layouts/AdminLayout'));However, I need to remember that dynamic imports within
MyAppcan't be used synchronously; I'd usenext/dynamicat the module scope. I’m planning to include options for TypeScript and JavaScript, and provide pros and cons. My main focus will be on clear, code-level instructions, particularly emphasizing the Next 13 app router, while also offering the Pages Router variant. Below are two solid ways to implement a multi-layout system in Next.js, depending on whether you’re using the App Router (Next.js 13+) or the Pages Router (classic/pagessetup).
1. App Router (Next.js 13+/14) – Native Multi-Layout via Route Groups
If you’re using the
app/directory, Next.js already has first-class support for route-based layouts. You don’t need a custom_app—you just define differentlayout.tsxfiles in different route segments.Example folder structure
app/ (public)/ layout.tsx # Public layout page.tsx # / about/ page.tsx # /about (dashboard)/ layout.tsx # Dashboard layout page.tsx # /dashboard settings/ page.tsx # /dashboard/settings(public)and(dashboard)are route groups: they don’t affect the URL, but they let you group routes under different layouts.app/(public)/layout.tsx// app/(public)/layout.tsx import type { ReactNode } from 'react'; export default function PublicLayout({ children }: { children: ReactNode }) { return ( <html lang="en"> <body> <header>Public Site Header</header> <main>{children}</main> <footer>Public Footer</footer> </body> </html> ); }app/(dashboard)/layout.tsx// app/(dashboard)/layout.tsx import type { ReactNode } from 'react'; export default function DashboardLayout({ children }: { children: ReactNode }) { return ( <html lang="en"> <body> <aside>Dashboard Sidebar</aside> <section>{children}</section> </body> </html> ); }Now:
/,/about→ usePublicLayout/dashboard,/dashboard/settings→ useDashboardLayout
Each layout is code-split and loaded only for the routes under its group. “Dynamic” selection is handled by the router itself.
If you want more layout variations, add more route groups and
layout.tsxfiles.
2. Pages Router (
/pages) – Dynamic Layouts in_app.tsxIf you’re in the
pages/world, you build a multi-layout system yourself via_app.tsx.You have two common patterns:
- A. Per-page
getLayoutfunction - B. Global route-based layout switch (using
router.pathname)
You can mix both if needed.
2A. Per-page
getLayoutpattern1) Define layout components
// components/layouts/MainLayout.tsx import type { ReactNode } from 'react'; export function MainLayout({ children }: { children: ReactNode }) { return ( <div> <header>Main Navbar</header> <main>{children}</main> </div> ); } // components/layouts/AdminLayout.tsx export function AdminLayout({ children }: { children: ReactNode }) { return ( <div className="admin-shell"> <aside>Admin Sidebar</aside> <main>{children}</main> </div> ); }2) Extend NextPage to support
getLayout// pages/_app.tsx import type { ReactElement, ReactNode } from 'react'; import type { AppProps } from 'next/app'; import type { NextPage } from 'next'; import { MainLayout } from '../components/layouts/MainLayout'; export type NextPageWithLayout = NextPage & { getLayout?: (page: ReactElement) => ReactNode; }; type AppPropsWithLayout = AppProps & { Component: NextPageWithLayout; }; export default function MyApp({ Component, pageProps }: AppPropsWithLayout) { const getLayout = Component.getLayout ?? ((page) => <MainLayout>{page}</MainLayout>); // default layout return getLayout(<Component {...pageProps} />); }3) Assign layouts on each page
// pages/index.tsx import type { ReactElement } from 'react'; import type { NextPageWithLayout } from './_app'; import { MainLayout } from '../components/layouts/MainLayout'; const HomePage: NextPageWithLayout = () => { return <div>Public home page</div>; }; HomePage.getLayout = function getLayout(page: ReactElement) { return <MainLayout>{page}</MainLayout>; }; export default HomePage;// pages/admin/index.tsx import type { ReactElement } from 'react'; import type { NextPageWithLayout } from '../_app'; import { AdminLayout } from '../../components/layouts/AdminLayout'; const AdminHome: NextPageWithLayout = () => { return <div>Admin dashboard</div>; }; AdminHome.getLayout = function getLayout(page: ReactElement) { return <AdminLayout>{page}</AdminLayout>; }; export default AdminHome;This lets each page specify its own layout and is highly flexible.
2B. Route-based layout switching in
_app.tsxIf you’d rather not touch every page, choose layouts by route patterns in
_app.tsx.1) Optionally dynamically import layouts (for code splitting)
// pages/_app.tsx import type { AppProps } from 'next/app'; import type { ReactNode } from 'react'; import dynamic from 'next/dynamic'; import { useRouter } from 'next/router'; const MainLayout = dynamic(() => import('../components/layouts/MainLayout').then(m => m.MainLayout)); const AdminLayout = dynamic(() => import('../components/layouts/AdminLayout').then(m => m.AdminLayout)); const AuthLayout = dynamic(() => import('../components/layouts/AuthLayout').then(m => m.AuthLayout), { ssr: false, // only if you specifically want client-only }); function getLayoutForRoute(pathname: string): (children: ReactNode) => ReactNode { if (pathname.startsWith('/admin')) { return (children) => <AdminLayout>{children}</AdminLayout>; } if (pathname.startsWith('/auth')) { return (children) => <AuthLayout>{children}</AuthLayout>; } return (children) => <MainLayout>{children}</MainLayout>; } export default function MyApp({ Component, pageProps }: AppProps) { const router = useRouter(); const wrapWithLayout = getLayoutForRoute(router.pathname); return wrapWithLayout(<Component {...pageProps} />); }Now layouts are chosen automatically:
/admin/*→AdminLayout/auth/*→AuthLayout- everything else →
MainLayout
You can make the mapping more declarative:
// in _app.tsx const layoutConfig = [ { pattern: /^\/admin/, Layout: AdminLayout }, { pattern: /^\/auth/, Layout: AuthLayout }, ]; const match = layoutConfig.find(({ pattern }) => pattern.test(router.pathname)); const Layout = match?.Layout ?? MainLayout; return ( <Layout> <Component {...pageProps} /> </Layout> );
When to use which approach?
-
App Router (
app/)
Use route groups andlayout.tsx– it’s the idiomatic Next.js 13+/14 way and gives you nested, route-based layouts out of the box. -
Pages Router (
pages/)- Need per-page control? Use
getLayout. - Want global, route-pattern based behavior? Use router-based switching in
_app.tsx.
- Need per-page control? Use
If you tell me which router/version you’re on and what layouts you need (e.g.,
public,dashboard,auth), I can give you a ready-made folder structure and exact code tailored to that setup.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.