Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Layouts and the root layout

A layout is a component that wraps pages and holds the parts they share: a header, a menu, a footer. You describe the layout once, and Next.js inserts the right page into it.

The root layout

The app/layout.tsx file was already created by the tool. It is the root layout: it is required and wraps every page of the site. Let us simplify it:

// app/layout.tsx
import './globals.css';
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <header>My blog</header>
        {children}
        <footer>© 2025 Anna</footer>
      </body>
    </html>
  );
}

Next.js passes the current page in the children prop. Open / and /about — both pages have the header and footer, only the middle changes.

Why html and body are here

Only the root layout contains the html and body tags — Next.js does not add them for you. The lang attribute tells the browser and search engines the page language.

A section layout

A layout can go in any folder. It wraps the pages of that folder and all nested ones. Create app/posts/layout.tsx:

// app/posts/layout.tsx
export default function PostsLayout({ children }: { children: React.ReactNode }) {
  return (
    <section>
      <aside>Topics: React, Next.js, CSS</aside>
      {children}
    </section>
  );
}

Now /posts and every address inside /posts/... show the topics block, while the home page does not.

Nested layouts

Layouts nest inside each other following the folders:

AddressWhat wraps the page
/app/layout.tsx
/aboutapp/layout.tsx
/postsapp/layout.tsx, then app/posts/layout.tsx

The layout survives navigation

When you move between pages of one section, the layout is not created again: its state, such as an open menu or text in a search field, is kept. Only the page re-renders.

Common mistake

Adding html and body tags to a nested layout. A second body ends up inside the first, the browser gets invalid HTML and React reports a hydration error. These tags belong only in app/layout.tsx; other layouts return ordinary markup such as section or div.

Thanks for reading!

Donate to the site — we work hard for you.