Topic 25 of 47
Root Layout
Overview
The Root Layout (app/layout.tsx) is required at the top level of the app directory. It defines the foundational HTML skeleton (<html> and <body> tags) and wraps every page in your application.
Syntax
tsx
// app/layout.tsx
import './globals.css';
export const metadata = {
title: 'My App',
description: 'App description',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Header />
{children} {/* Pages render here */}
<Footer />
</body>
</html>
);
}Common Pitfalls
- You cannot use 'use client' in the Root Layout if it exports metadata. Keep the Root Layout as a Server Component.
- Only the Root Layout can contain <html> and <body> tags. Nested layouts should only return <div> or semantic tags.
Real-World Example
Adding global providers (like ThemeProvider) in the root layout:
example
tsx
// app/layout.tsx
import { ThemeProvider } from '@/components/ThemeProvider';
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'] });
export default function RootLayout({ children }) {
return (
<html lang="en" suppressHydrationWarning>
<body className={inter.className}>
<ThemeProvider attribute="class" defaultTheme="system">
{children}
</ThemeProvider>
</body>
</html>
);
}