乐闻世界logo
搜索文章和话题

What are the differences between Pages Router and App Router in Next.js?

2月17日 23:32

Next.js provides two main routing architectures: Pages Router and App Router. They have significant differences in design philosophy, features, and performance.

Pages Router

Pages Router is Next.js's traditional routing system, based on the pages directory.

Features

  1. Simple File Structure
shell
pages/ index.js about.js blog/ [slug].js
  1. Data Fetching Methods
  • getStaticProps: Fetch data at build time
  • getServerSideProps: Fetch data on each request
  • getStaticPaths: Define paths for dynamic routes
  1. Lifecycle
  • Supports React's full lifecycle
  • Uses useEffect for client-side data fetching
  1. Route Hooks
javascript
import { useRouter } from 'next/router'; const router = useRouter(); console.log(router.pathname, router.query);

Pros

  • Mature and stable, with comprehensive documentation and community support
  • Gentle learning curve
  • Suitable for small to medium projects

Cons

  • Doesn't support nested routes
  • Doesn't support server components
  • Limited performance optimization

App Router

App Router is the new routing system introduced in Next.js 13+, based on the app directory.

Features

  1. File Structure
shell
app/ page.js layout.js about/ page.js blog/ [slug]/ page.js
  1. Server Components and Client Components
javascript
// Server component (default) async function BlogList() { const posts = await fetch('https://api.example.com/posts').then(r => r.json()); return <div>{posts.map(post => <Post key={post.id} {...post} />)}</div>; } // Client component 'use client'; import { useState } from 'react'; function InteractiveComponent() { const [count, setCount] = useState(0); return <button onClick={() => setCount(c => c + 1)}>{count}</button>; }
  1. Data Fetching
javascript
// Fetch data directly in the component async function Page() { const data = await fetch('https://api.example.com/data', { next: { revalidate: 60 } // ISR }).then(r => r.json()); return <div>{data.content}</div>; }
  1. Layout System
javascript
// app/layout.js export default function RootLayout({ children }) { return ( <html> <body> <Header /> {children} <Footer /> </body> </html> ); }
  1. Route Hooks
javascript
import { useParams, usePathname } from 'next/navigation'; const params = useParams(); const pathname = usePathname();

Pros

  • Supports server components, reducing client-side JavaScript
  • Supports nested routes and layouts
  • Better performance and user experience
  • More modern API design

Cons

  • Steeper learning curve
  • Relatively new, ecosystem still developing
  • Need to understand the difference between server and client components

Main Differences Comparison

FeaturePages RouterApp Router
Directorypages/app/
Server ComponentsNot supportedSupported
Nested RoutesNot supportedSupported
Layout SystemLimitedPowerful
Data FetchinggetStaticProps/getServerSidePropsDirectly in component
Route Hooksnext/routernext/navigation
File Conventionindex.jspage.js
Loading StatesManual implementationAutomatic loading.js support
Error HandlingManual implementationAutomatic error.js support
Streaming RenderingNot supportedSupported

Migration Recommendations

When to Use Pages Router

  • Existing projects already using Pages Router
  • Small projects that don't need complex features
  • Team more familiar with Pages Router

When to Use App Router

  • New projects
  • Need server components to optimize performance
  • Need nested routes and complex layouts
  • Need better SEO and performance

Mixed Usage

Next.js allows using both routers simultaneously:

  • pages/ directory uses Pages Router
  • app/ directory uses App Router
javascript
// Both directories can coexist pages/ api/ hello.js // API routes app/ page.js // Main page

Best Practices

  1. Prioritize App Router for new projects: Get better performance and development experience
  2. Gradual migration: Existing projects can gradually migrate pages to App Router
  3. Use server components wisely: Make components that don't need interactivity server components
  4. Leverage layout system: Use nested layouts to share UI
  5. Maintain consistency: Try to use one router consistently in a project

Choosing which router to use depends on project requirements, team experience, and performance needs. App Router represents the future direction of Next.js, but Pages Router remains a reliable choice.

标签:Next.js