Migrating from Pages Router to App Router in Next.js – A Gentle, Step-by-Step Guide for Modern Web Development

Next.js 13 introduced the App Router — a modern, powerful alternative to the classic Pages Router. This article walks you through a smooth migration process, including version upgrades, layout setup, component updates, data fetching, API routes, styling, and codemods. You’ll learn how to transition gradually while keeping your app stable and future-ready.

App RouterPages RouterNext.js MigrationServer ComponentsCodemods

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۲۲ آذر ۱۴۰۴

Why Migrate to App Router?


The App Router in Next.js 13+ offers:

  • Server Components: Less JavaScript sent to the client
  • Streaming: Faster page loads with React Suspense
  • Smart Caching: Built-in route and data caching
  • Simpler Data Fetching: No need for getStaticProps or getServerSideProps
  • Natural Layouts: Built-in layout support without custom wrappers

Golden Tip: You can use both routers together and migrate incrementally.


Step 1: Update Versions


npm install next@latest react@latest react-dom@latest
npm install -D eslint-config-next@latest

Restart ESLint in VS Code: Ctrl+Shift+P → "ESLint: Restart ESLint Server"


Step 2: Upgrade Core Components


  • <Image>: Use next/image instead of next/future/image
  • <Link>: No need to nest <a> inside <Link>
  • <Script>: Move beforeInteractive scripts to app/layout.tsx
  • Fonts: Use next/font for built-in font optimization

Step 3: Create the app Directory


project-root/
├── app/
├── pages/
└── ...

Step 4: Create Root Layout


// app/layout.tsx
export const metadata = {
  title: 'My Website',
  description: 'Built with love and Next.js',
}

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}

This replaces _app.tsx and _document.tsx.


Step 5: Migrate next/head → Metadata API


// Before
<Head><title>Page Title</title></Head>

// After
export const metadata = { title: 'Page Title' }

Step 6: Migrate Pages to App Router


Pages RouterApp Router
pages/index.jsapp/page.js
pages/about.jsapp/about/page.js
pages/blog/[slug].jsapp/blog/[slug]/page.js

Step 7: Migrate Data Fetching


  • getStaticPropsfetch(..., { cache: 'force-cache' })
  • getServerSidePropsfetch(..., { cache: 'no-store' })
  • getStaticPathsgenerateStaticParams()

Step 8: Migrate API Routes


// app/api/hello/route.ts
export async function GET() {
  return Response.json({ message: 'Hello World!' })
}

Step 9: Migrate Routing Hooks


'use client'
import { usePathname, useSearchParams } from 'next/navigation'

const pathname = usePathname()
const searchParams = useSearchParams()

Step 10: Styling


  • Global CSS: Import in app/layout.tsx
  • Tailwind: Add app to tailwind.config.js content array

Step 11: Using Both Routers Together


Hard navigation between pages and app causes full reload. For soft navigation, use router.push() inside App Router.


Step 12: Use Codemods


npx next-codemod next-image-experimental ./pages
npx next-codemod new-link ./pages

نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

ادامه

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

ادامه

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

ادامه

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

ادامه

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

ادامه

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

ادامه