The Pages Router for legacy apps

Intermediate · 16 min

Read and maintain a Pages Router app: its data functions and special files, how it coexists with the App Router, and a page-by-page path for migrating it.

Before thisThe App Router and the Pages RouterUpgrading and the codemods

leerob · 16 min

The Pages Router for legacy apps

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by leerobReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • The Pages Router maps files in pages/ to routes and fetches data with getStaticProps, getStaticPaths, and getServerSideProps; it is still supported in Next.js 16, though the docs recommend the App Router.
  • pages/ and app/ can live in the same project, but the same URL cannot be in both: the build fails with an error that both routers match the path.
  • Each Pages Router idea has an App Router replacement: _app and _document become the root layout, API routes become route handlers, and data functions become async Server Components and generateStaticParams.
  • Navigating between a Pages Router route and an App Router route is a hard navigation, and next/link does not prefetch across routers.
  • Migrate one route at a time, keep _app and _document until the last page has moved, and move shared components behind next/compat/router while both routers exist.

The router you will meet in real code

Next.js 13 introduced the App Router. Before that, every Next.js app used what is now called the Pages Router. Many production apps still do, and the docs say it is still supported in newer versions while recommending the App Router for React’s latest features. You will probably read this code before you write any App Router code at work.

This lesson is the field guide: what the old model looks like, how it coexists with the new one, and how to move over without a rewrite.

How the Pages Router works

Every file in pages/ is a route. pages/index.tsx is /, pages/posts/[id].tsx is /posts/:id, and pages/api/hi.ts is an API endpoint. There are no layout files. Instead, two special files wrap everything: _app renders each page and holds global state or providers, and _document customizes the HTML shell.

Data is fetched by exporting a function next to the component, and its result arrives as props:

// pages/index.tsx
import Head from 'next/head'
import type { GetStaticProps } from 'next'

export const getStaticProps: GetStaticProps = async () => ({
  props: { n: 1 },
  revalidate: 60,
})

export default function Home({ n }: { n: number }) {
  return (
    <>
      <Head><title>Home</title></Head>
      <h1>Home {n}</h1>
    </>
  )
}

Three functions cover it. getStaticProps runs at build time, and with revalidate it becomes ISR. getStaticPaths lists the paths for a dynamic route. getServerSideProps runs on every request. The component itself runs in the browser too, so the whole page is a client-side React tree that is also server-rendered; there is no Server Component split. What Next.js is and why it exists gave the history, and the React roadmap covers the component model underneath.

I built a project with a pages/ directory and a small app/ directory on 16.4.6. The build printed two tables:

Route (app)
┌ ○ /_not-found
└ ○ /new

Route (pages)         Revalidate  Expire
┌ ● /                         1m      1y
├   /_app
├ ƒ /api/hi
└ ƒ /posts/[id]

The getStaticProps page shows ● with a one-minute revalidate, the getServerSideProps page and the API route are ƒ. Reading the route table works the same as for an App Router app.

Coexistence rules

Both routers can live in one project. That is what makes gradual migration possible, and the docs describe app as designed to work alongside pages for page-by-page moves. The rules:

  • One owner per URL. Adding pages/new.tsx next to app/new/page.tsx fails the build: “App Router and Pages Router both match path: /new”. Move a route, do not copy it.
  • Hard navigations. Moving between a route served by one router and a route served by the other is a full page load, and next/link prefetching does not cross over. The docs link a Vercel guide on optimizing those navigations.
  • Layouts do not cross. Styles in app/layout.tsx do not apply to pages/*, which is why _app and _document stay until the end.
  • Different routing hooks. app uses useRouter, usePathname, and useSearchParams from next/navigation. For components shared by both routers, the docs point to useRouter from next/compat/router, then to switch to next/navigation once only app uses the component.

The mapping

Pages Router App Router
_app.js and _document.js root app/layout.js
_error.js error.js, more granular
404.js not-found.js
pages/api/* route.js route handlers
getServerSideProps async Server Component reading request data
getStaticProps fetch or a database call in a Server Component
getStaticPaths generateStaticParams
getStaticProps with revalidate Incremental Static Regeneration through revalidation
next/head the Metadata API

Take the server-rendered case. This Pages Router route:

// pages/posts/[id].tsx
import type { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async ({ params }) => ({
  props: { id: params?.id ?? null },
})

export default function Post({ id }: { id: string }) {
  return <h1>Post {id}</h1>
}

becomes this one in app/posts/[id]/page.tsx:

export default async function Post({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  return <h1>Post {id}</h1>
}

No props plumbing; the component is the data function. Built in 16.4.6 without Cache Components, it shows as ƒ, like the original. With Cache Components on, that same file fails the build until you add Suspense or caching, as described in build output. The docs also note that if an API route only existed so the client could call an external API, a Server Component can now fetch that data directly.

A migration order

  1. Get current first. Upgrade within the Pages Router, using the upgrade tooling. A legacy app on an old version has two problems; separate them.
  2. Create app/ with a root layout. Copy the contents of _app and _document, such as global styles. Move React context providers into a Client Component. Keep the old files.
  3. Move leaf routes first. Pick simple pages, convert data functions, and delete the pages/ version.
  4. Swap the hooks from next/router to next/navigation, and from next/head to the Metadata API.
  5. Leave API routes alone until it is convenient. The docs say they keep working unchanged in pages/api.
  6. Delete _app, _document, and then pages/ when the last route has moved.

Do not rebuild everything in one pull request. The lasting value of the App Router is Server Components and streaming; do them route by route and the app stays deployable at each step.

When to stay put

Staying on pages/ is a legitimate choice. It still works, the docs keep a full Pages Router section, and a stable internal tool may never repay the migration. What you give up is the App Router’s features. Next.js 16’s headline work, such as Cache Components, is built on it.

What the video covers

Lee Robinson’s video is linked from the official migration guide. From its description and chapters, it moves routes from pages/ to app/ and covers static routes (0:14), Server Components, Client Components, and mixing the two (4:15), next/head and the Metadata API (6:22), getServerSideProps (7:45), async/await in Server Components (9:28), passing data to Client Components, fetch() and caching (13:03), Incremental Static Regeneration (14:02), and layouts versus _app.js and _document.js (14:26). Transcripts were unavailable, so I rely on those.

It dates from June 2023, during Next.js 13 and 14, so its caching section is out of date for 16, and it shows the App Router side more than Pages Router internals. The runner-up, Brad Traversy’s 2021 crash course, is the other way round: its chapters cover pages and routing, _document, getStaticProps, getServerSideProps, getStaticPaths, exporting a static site, and API routes, all on a Next.js 10 era Pages Router. It is long, with chapters you can jump between, and its captions include many languages but I did not check the audio.

Where this fits

This closes the Next.js roadmap. You went from what the framework is, through routing, components, data, mutations, rendering, styling, security, and testing, to shipping and maintaining an app, and now to inheriting one. Where to go next depends on what you build: the React roadmap for the component model, TypeScript for typing, and Node.js for what runs under next start.

Check yourself

  1. 01What happens if pages/new.tsx and app/new/page.tsx both exist?

    The build fails with 'App Router and Pages Router both match path: /new'. Next.js does not support both routers matching the same path, so a page has to be removed from pages/ when its replacement is added to app/.

  2. 02Which App Router feature replaces getStaticPaths, and which replaces getStaticProps with revalidate?

    generateStaticParams replaces getStaticPaths. For getStaticProps with revalidate, you fetch in a Server Component and use the App Router's revalidation features for Incremental Static Regeneration.

  3. 03Why keep _app.js and _document.js while migrating?

    Styles and providers in app/layout.js do not apply to routes in pages/, so deleting them early would break every page that has not moved yet. Copy their contents into the root layout and delete the old files once the last route is migrated.

  4. 04What is the cost of a user clicking a link from a Pages Router page to an App Router page?

    It is a hard navigation, a full page load, and next/link prefetching does not cross routers, so the transition is slower than an in-router one until the migration finishes.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark