FrontendDeveloper.in

React question detail

What are the differences between page router and app router in nextjs?

Next.js provides two different routing systems: the Page Router (traditional) and the App Router (introduced in Next.js 13). The App Router is built on React Server Components and offers more powerful features for modern web applications.

Here are the main differences between them:

FeaturePage RouterApp Router
DirectoryUses pages/ directoryUses app/ directory
RoutingFile-based routing with files like pages/about.jsFile-based routing with folders and special files like app/about/page.js
ComponentsAll components are Client Components by defaultAll components are Server Components by default
LayoutsCustom _app.js and _document.js for shared layoutsNative nested layouts using layout.js files
Data FetchingUses getServerSideProps, getStaticProps, and getInitialPropsUses async/await in Server Components with native fetch
Loading StatesManual implementation requiredBuilt-in loading.js for streaming and suspense
Error HandlingCustom _error.js pageBuilt-in error.js for error boundaries at any level
StreamingLimited supportBuilt-in support for streaming with Suspense
Server ActionsNot availableNative support for server-side mutations
MetadataUsing Head component from next/headNative Metadata API with metadata object or generateMetadata function
RenderingSSR, SSG, ISR, and CSRSSR, SSG, ISR, CSR plus React Server Components

Example of Page Router structure:

pages/
├── index.js          // Home page (/)
├── about.js          // About page (/about)
├── _app.js           // Custom App component
├── _document.js      // Custom Document
└── posts/
└── [id].js       // Dynamic route (/posts/:id)

Example of App Router structure:

app/
├── page.js           // Home page (/)
├── layout.js         // Root layout
├── loading.js        // Loading UI
├── error.js          // Error UI
├── about/
│   └── page.js       // About page (/about)
└── posts/
└── [id]/
└── page.js   // Dynamic route (/posts/:id)

Note: The App Router is recommended for new Next.js applications as it provides better performance, simpler data fetching patterns, and improved developer experience with React Server Components.

Back to all React questions
Get LinkedIn Premium at Rs 399