tezvyn:

Next.js: Pages Router vs. App Router

AI-drafted, machine-checkedSource: nextjs.orgbeginner

The App Router treats UI as a tree of components, while the older Pages Router treats it as a collection of separate pages. Use App Router for new projects to leverage layouts and Server Components.

WHY IT EXISTS Next.js needed a more powerful routing system to leverage modern React features like Server Components and Suspense. The original Pages Router was effective but coupled data fetching to entire pages, which limited layout flexibility, code colocation, and UI streaming capabilities.

THE MENTAL MODEL The Pages Router is page-centric. A file in the pages directory becomes a route, and you attach data to the whole page using special exported functions. The App Router is component-centric. You build routes from page.js files, but the UI itself is a tree of components where server-side components can fetch their own data independently.

HOW IT WORKS In the Pages Router, a file like pages/users/[id].js is a route. You export an async function like getServerSideProps from that file to fetch data for the entire page. In the App Router, the route would be app/users/[id]/page.js. This file contains a React Server Component that can use async/await directly to fetch data. Shared UI is handled by layout.js files, and components needing browser-only APIs or state require a "use client" directive.

WHEN TO USE IT Use the App Router for all new Next.js applications. It provides superior features like nested layouts, fine-grained caching, Server Actions for mutations, and streaming UI from the server. You will encounter the Pages Router when maintaining or migrating older Next.js projects.

WHEN NOT TO USE IT There is no longer a strong reason to start a new project with the Pages Router. The App Router is the recommended, more powerful paradigm. You might only stick with the Pages Router if migrating an existing, large, and stable application is not feasible.

ONE CANONICAL EXAMPLE In the Pages Router, fetching a user profile required a pages/profile.js file with a getServerSideProps function that fetches user data and passes it as props. In the App Router, the app/profile/page.js file can be an async component that directly awaits the data fetch inside its own function body, simplifying the code and colocating the data dependency with the component that uses it.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.