page.js and layout.js in Next.js

In the Next.js App Router, page.js and layout.jsplay different roles. Understanding the difference is essential for building scalable and maintainable applications.

What is page.js?

page.js defines a route and represents the main content of a page. Every folder that contains a page.js becomes accessible as a URL in the browser.

app/page.js        → /
app/blog/page.js   → /blog

Each page.js is responsible only for the content of that specific route.

What is layout.js?

layout.js is used to define shared UI that persists across multiple pages, such as headers, footers, sidebars, or navigation menus.

app/layout.js     → Root layout
app/blog/layout.js → Blog layout

Layouts wrap around pages and remain mounted when navigating between routes.

Key Difference Between page.js and layout.js

page.js   → Defines route content
layout.js → Defines shared structure

Real World Example

Think of a website like a shopping mall.

The mall building, entrance, and elevators remain the same. Individual shops change as you move around.

layout.js → Mall building (header, footer, sidebar)
page.js   → Individual shops (content)

Why This Separation Matters

Separating layout and page logic improves performance, keeps code organized, and makes large applications easier to maintain and scale.