Next.js Tutorial
- Next.js Introduction
- Next.js Installation
- Project Structure
- Pages & Routing
- Dynamic Routing
- Linking & Navigating
- Data Fetching (SSR)
- Data Fetching (SSG)
- Client-Side Rendering
- API Routes
- Layouts & Components
- Styling
- Image Optimization
- Font Optimization
- Script Optimization
- Middleware
- Environment Variables
- Error Handling
- Authentication
- React Server Components
- Server Actions
- Suspense & Streaming
- Caching & Revalidation
- TypeScript Integration
- Deployment
Layouts & Components
In standard React development, you often have a NavBar and Footer that need to appear on every single page. If you manually import them into every file, your code becomes repetitive and difficult to maintain. Next.js solves this with Layouts.
The `layout.js` file (App Router)
In the App Router, you can define an overarching layout simply by creating a layout.js file in a directory. This layout will wrap every page and nested directory beneath it.
// app/layout.js
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<Navbar />
{/* The current page gets rendered inside {children} */}
<main>{children}</main>
<Footer />
</body>
</html>
);
}Nested Layouts
Layouts can be deeply nested. If you have an admin dashboard, you can define a root layout with a generic NavBar, and then an `app/dashboard/layout.js` file that adds a specific Admin Sidebar. The user will see both layouts combined!
Layouts in the Pages Router (`_app.js`)
In the older Pages router architecture, global layouts are applied inside the pages/_app.js file.
// pages/_app.js
import Layout from '../components/Layout';
import '../styles/globals.css';
export default function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}Component Architecture
Where should you place non-page React components (like Buttons, Modals, Forms)? Next.js does not enforce a strict rule, but conventionally, developers create a components/ directory at the root (or inside src/).
my-app/
├── app/
│ └── page.js
└── components/
├── ui/
│ ├── Button.js
│ └── Modal.js
└── layout/
├── Navbar.js
└── Footer.js
Because these folders are named `components`, Next.js knows NOT to treat them as routable pages.
Metadata in Layouts
In the App router, Layouts are an excellent place to define top-level SEO Metadata for your application.
// app/layout.js
export const metadata = {
title: 'My Awesome Site',
description: 'Built with Next.js',
};Conclusion
Properly structuring your Next.js Layouts saves hundreds of lines of boilerplate code. Now that our components are rendering onto the screen cleanly, we must learn how to make them look beautiful with Styling.