In Next.js 13, the App Router was introduced with several exciting features, such as layouts, error boundaries, loading indicators, and more. However, some developers face challenges when managing multiple layouts at the same route level. Below, Iβll show you the best way to structure and maintain clean, convenient layouts for such scenarios.
Step 1: Create a Root Layout (Optional)
A root layout is useful for defining global components or context providers for your entire app. However, if your app doesnβt require global configurations, you can skip this step.
// app/layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html>
<body>
<RootProviders>
{children}
</RootProviders>
</body>
</html>
);
}
Step 2: Define Layouts for Specific Route Groups
Suppose we need a Header
and Footer
for the /home
and /contact
pages. To achieve this, we can use Next.js Route Groups.
For example, weβll create a route group called (marketing)
and place our pages inside it. Pages like app/(marketing)/home/page.tsx
and app/(marketing)/contact/page.tsx
will use the app/(marketing)/layout.tsx
layout.
// app/(marketing)/layout.tsx
export default function MarketingLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<Providers>
<Header />
<main>{children}</main>
<Footer />
</Providers>
);
}
Step 3: Create Layouts for Other Route Groups
Similarly, for pages like /policy
and /tos
, we can create a new route group called (legal)
and define a specific layout for it.
// app/(legal)/layout.tsx
export default function LegalLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<>
<Header />
<main className="container mx-auto">{children}</main>
</>
);
}
Key Benefits
Using this approach, you can:
- Maintain multiple layouts for routes at the same level.
- Keep your project structure clean and organized.
- Implement specific features, such as Google Analytics, for certain layouts. For example, you could add analytics tracking specifically within the
LegalLayout
for pages like/policy
and/tos
.
By leveraging Route Groups and Layouts, Next.js empowers you to create modular, scalable, and maintainable architectures for your applications.
Top comments (0)