Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 72 ยท Deployment and Production

Upgrading and Migrating from Pages Router

Upgrade to Next.js 15 and 16 with codemods, handle async request APIs and caching changes, and move a Pages Router app to the App Router step by step.

Next.js ships a new major version about once a year, and most real projects are older than the tutorial you are reading. Two jobs come up again and again: upgrading to a newer version, and migrating an older app built on the Pages Router (the pages/ folder) to the App Router (the app/ folder). Both are manageable when you do them in small, tested steps instead of one big weekend rewrite.

This lesson explains how to upgrade safely, what changed in versions 15 and 16 that tends to break code, and how to move from pages/ to app/ one route at a time while the site stays live. The commands and code here are real Next.js code in read-only blocks. The runnable examples are small Node.js stand-ins: a mini codemod that rewrites code, and a planner that maps pages/ files to app/ files.

Versions change quickly. The facts below describe Next.js 15 and 16. Before you upgrade a real project, read the official upgrade guide for your exact target version, because details such as option names and defaults can shift between minor releases.

Upgrade in small steps

A safe upgrade routine

Clean branch Start from a green test run.
Run the codemod Let tools do the boring edits.
Read the diff Review every change yourself.
Test and build Run tests, then next build.

One major version at a time.

1 / 2

Follow the same routine every time:

  1. Work on a branch, with passing tests and a successful next build before you touch anything.
  2. Jump one major version at a time (13 to 14 to 15 to 16), so each failure points at a single cause.
  3. Run the official upgrade tool. It updates next, react and react-dom and offers the codemods that apply to your jump:
Terminal
npx @next/codemod@canary upgrade latest
  1. Review the diff by hand, run your tests, run next build, and click through the app.

If you prefer manual control, install the packages yourself with npm install next@latest react@latest react-dom@latest and run individual codemods afterwards.

What a codemod is

A codemod is a program that edits source code by understanding its structure, so one command can apply the same change to hundreds of files. Next.js publishes codemods in the @next/codemod package. Useful ones include next-async-request-api (adds the await calls described below), middleware-to-proxy (renames the file and function, see Middleware and the Proxy File) and next-lint-to-eslint-cli (replaces the removed next lint command). Run one on a folder like this:

Terminal
npx @next/codemod@canary next-async-request-api .

Codemods handle the common shape of code. They leave a comment or skip code they cannot safely change, so searching the diff for @next/codemod comments is part of the review. The stand-in below does the same job in miniature with a few text patterns. A real codemod works on the syntax tree, which is much more reliable than text patterns, but the idea is identical: read source, apply rules, report what changed.

Node.js A mini codemod for async request APIs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output shows the three kinds of edits the real codemod makes for you: params and searchParams are awaited, cookies() is awaited, and the component becomes async. Files without any of these patterns are left alone, which is what you want from a tool you run on a whole repository.

What changed in Next.js 15

Version 15 is where "uncached by default" and "asynchronous request APIs" arrived. The changes that most often break upgrades:

  • Async request APIs. cookies(), headers() and draftMode(), and the params and searchParams props of pages, layouts and handlers, now return promises. Version 15 still allowed synchronous access with a warning. Version 16 removes that. Always await them (see Dynamic Routes and Cookies and Headers).
  • Caching defaults flipped. fetch requests are no longer cached by default, and GET Route Handlers are no longer cached by default. Before version 15, a plain fetch was cached forever, which surprised many people. Now you opt in to caching explicitly, as Caching in Next.js: the Big Picture explains.
  • Client router cache. Page segments are no longer reused from the browser's router cache on navigation by default (staleTimes is 0 for pages), so links show fresh data more often.
  • React 19. The App Router needs it. Libraries that depend on old React internals may need updates.
  • Removed or renamed options. For example runtime: 'experimental-edge' became 'edge', and the geo and ip properties of NextRequest were removed (read headers such as x-forwarded-for instead).

What changed in Next.js 16

Version 16 builds on 15. The headline changes:

  • Turbopack is the default bundler for next dev and next build. A project with a custom webpack function in its config must either port that setup or opt out with the --webpack flag.
  • middleware became proxy. The file is proxy.ts and the exported function is proxy. It runs on the Node.js runtime. The old middleware.ts name still works for the Edge runtime but is deprecated.
  • Synchronous access to request APIs is gone. Un-awaited params, cookies() and the rest now fail instead of warning.
  • Cache Components. The opt-in model built around the "use cache" directive, enabled with cacheComponents: true. It replaces the earlier experimental flags for dynamic IO and partial prerendering, and replaces some route segment options (export const dynamic, revalidate) when it is on. See The use cache Directive and Cache Components.
  • Cache APIs. revalidateTag now expects a cache-life profile as a second argument (for example 'max'), and the one-argument form is deprecated. updateTag gives read-your-own-writes inside Server Actions, and refresh refreshes uncached data (see Revalidating Data).
  • next lint was removed. Run ESLint or Biome directly (see TypeScript, ESLint and Typed Routes).
  • Image changes. next/legacy/image and images.domains are deprecated in favor of next/image and remotePatterns, and the default minimum cache time for optimized images grew to four hours.
  • Parallel routes need an explicit default.tsx in every slot, or the build fails (see Parallel and Intercepting Routes).
  • Higher minimums. Node.js 20.9 or newer and TypeScript 5.1 or newer.

You do not have to adopt Cache Components the day you upgrade. Treat it as a separate, later migration, with its own branch and tests.

Pages Router versus App Router

The Pages Router builds each file in pages/ into a page and gives it data through special functions. The App Router builds a tree of folders with layouts and Server Components. These are the mappings you will use most:

Pages Router App Router
pages/_app.tsx app/layout.tsx (providers, global CSS)
pages/_document.tsx app/layout.tsx (<html> and <body>)
pages/about.tsx app/about/page.tsx
pages/blog/[slug].tsx app/blog/[slug]/page.tsx
pages/api/x.ts app/api/x/route.ts
pages/404.tsx app/not-found.tsx
pages/_error.tsx, pages/500.tsx app/error.tsx and app/global-error.tsx
getServerSideProps an async Server Component that reads request data
getStaticProps data fetching in a Server Component, with caching or revalidate
getStaticPaths generateStaticParams
next/head the metadata object or generateMetadata
next/router next/navigation (useRouter, usePathname, useSearchParams, useParams)

Here is the same product page in both styles. First the Pages Router version:

TSX
// pages/products/[id].tsx
import Head from 'next/head';
import type { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async ({ params }) => {
  const res = await fetch('https://api.shop.test/products/' + params!.id);
  if (!res.ok) return { notFound: true };
  return { props: { product: await res.json() } };
};

export default function ProductPage({ product }: { product: { name: string } }) {
  return (
    <>
      <Head><title>{product.name}</title></Head>
      <h1>{product.name}</h1>
    </>
  );
}

And the App Router version. The data function disappears: the component fetches its own data, notFound() replaces the notFound return value, and metadata gets its own function.

TSX
// app/products/[id]/page.tsx
import { notFound } from 'next/navigation';
import type { Metadata } from 'next';

type Props = { params: Promise<{ id: string }> };

async function getProduct(id: string) {
  const res = await fetch('https://api.shop.test/products/' + id);
  if (!res.ok) return null;
  return (await res.json()) as { name: string };
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const product = await getProduct(id);
  return { title: product?.name ?? 'Not found' };
}

export default async function ProductPage({ params }: Props) {
  const { id } = await params;
  const product = await getProduct(id);
  if (!product) notFound();
  return <h1>{product.name}</h1>;
}

A request-level memoization (see Fetching Data in Server Components) means that calling getProduct in both places does not send two network requests.

Reading Pages Router code: the legacy APIs in detail

You will meet Pages Router code for years, in old projects, in tutorials and on job interviews. Here is what each legacy API does, so that you can read it and translate it. The code is read-only: it only runs inside a real Next.js project.

getStaticProps

Runs on the server at build time (and again when a page is revalidated). Whatever it returns in props is passed to the page component. The result is saved as static HTML plus a JSON file for client-side navigation.

TSX
// pages/posts/[slug].tsx (read-only)
import type { GetStaticProps, GetStaticPaths } from "next";

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const post = await getPost(params!.slug as string);
  if (!post) return { notFound: true }; // renders the 404 page
  return {
    props: { post },
    revalidate: 60, // Incremental Static Regeneration: rebuild at most once a minute
  };
};

It can also return { redirect: { destination, permanent } }. The revalidate number is incremental static regeneration (ISR): after 60 seconds, the next visitor still gets the old page while Next.js rebuilds it in the background. The App Router equivalent is export const revalidate = 60 or a cached fetch with next: { revalidate: 60 } (see Revalidation). On-demand rebuilds used res.revalidate("/posts/hello") in an API route; today you call revalidatePath or revalidateTag in a Server Action or Route Handler.

getStaticPaths and its fallback modes

For a dynamic route such as [slug], getStaticProps needs to know which pages to build. getStaticPaths lists them, and the fallback value decides what happens for a path that was not listed:

TSX
// pages/posts/[slug].tsx (read-only)
export const getStaticPaths: GetStaticPaths = async () => {
  const slugs = await getAllSlugs();
  return {
    paths: slugs.map((slug) => ({ params: { slug } })),
    fallback: "blocking", // false | true | "blocking"
  };
};
fallback Unknown path
false Answers 404. Only listed paths exist.
true Immediately shows a placeholder version of the page (router.isFallback is true), generates the page in the background, then swaps it in.
"blocking" Makes the first visitor wait while the page renders on the server, then caches it. No placeholder state.

In the App Router, the list becomes generateStaticParams, and export const dynamicParams = false plays the role of fallback: false. The default (dynamicParams = true) behaves like "blocking": unknown paths are rendered on demand and then cached. There is no placeholder mode, because streaming with loading.tsx (Loading, Error and Not Found) replaces it. The stand-in shows the three modes side by side.

Node.js getStaticPaths fallback modes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

getServerSideProps

Runs on every request, on the server only. It receives a context with params, query, req, res, locale and more. Use it when the page depends on the request (a cookie, a header, a query string). It cannot be combined with getStaticProps on the same page. The App Router equivalent is an async Server Component that reads await searchParams, await cookies() or await headers(), which makes the route dynamic (Dynamic APIs and Static vs Dynamic). The legacy getInitialProps is older and slower still: avoid it and replace it on sight.

_app.tsx and _document.tsx

  • pages/_app.tsx wraps every page. It receives Component and pageProps and renders them, so it is where global CSS was imported and where providers (theme, auth, data cache) were placed. It keeps state when users navigate, like a layout.
  • pages/_document.tsx customizes the HTML skeleton that wraps the page: <Html lang="en">, <Head>, <body> and the <Main /> and <NextScript /> placeholders. It renders only on the server, so it has no state and no event handlers.

Both are replaced by the root app/layout.tsx: it renders <html> and <body> itself, imports the global CSS and wraps children in providers (which must be a "use client" file, see Client Components and "use client").

next/head and the other Pages Router helpers

<Head> from next/head put tags such as <title> and <meta> in the document head. Every page repeated its own tags, and duplicates were resolved by a key. The App Router replaces it with the metadata export and generateMetadata (Metadata and SEO). In the same way, next/router is replaced by next/navigation (note that router.query is gone: use useParams() and useSearchParams()), and next/link no longer needs a child <a> tag since Next.js 13.

pages/api

An API route exports a default function with Node-style req and res:

TypeScript
// pages/api/subscribe.ts (read-only)
import type { NextApiRequest, NextApiResponse } from "next";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== "POST") return res.status(405).json({ error: "Method not allowed" });
  const { email } = req.body;
  return res.status(200).json({ subscribed: email });
}

In the App Router this becomes app/api/subscribe/route.ts with a named POST function that takes a Request and returns a Response; the method check is automatic (Route Handlers). API routes in pages/ keep working next to the App Router, so there is no hurry to move them.

Error pages

pages/404.tsx is a static page for unknown URLs, pages/500.tsx for server errors, and pages/_error.tsx is a catch-all that receives a statusCode. They map to not-found.tsx, error.tsx and global-error.tsx in the App Router, which are finer: each route segment can have its own.

Migrating incrementally

Both routers can live in the same project at the same time. Next.js looks in app/ and pages/ and serves each URL from whichever one defines it. That makes a gradual migration possible:

  1. Upgrade first, migrate second. Get to a current Next.js and React on the existing Pages Router app, with tests passing. Do not combine the two jobs.
  2. Create app/layout.tsx. It must contain <html> and <body>. Move global CSS imports here and add the providers that _app.tsx used to wrap around everything. Providers that use state or context must live in a small file marked "use client" (see Client Components and "use client").
  3. Migrate leaf routes first. Start with simple, low-traffic pages such as "About" or a legal page. Each one teaches you the pattern before you reach the complicated ones.
  4. Convert data fetching. Replace the getServerSideProps and getStaticProps pairs with async components. Replace getStaticPaths with generateStaticParams. Decide for each page whether it should be cached (Static vs Dynamic Rendering).
  5. Replace router imports. In the app/ directory, import from next/navigation, never from next/router. The new useRouter has no query or pathname or router events: use useParams, usePathname and useSearchParams instead.
  6. Leave API routes alone until the end. pages/api keeps working next to app/, and converting them to Route Handlers is optional and mechanical (see Route Handlers).
  7. Delete the old file once the new route works. A URL defined in both routers is a build error, and that is also your guard against forgetting something.

A few things have no direct equivalent. getInitialProps is not supported in app/, and the built-in i18n routing config of the Pages Router does not apply to the App Router (see Internationalization for the replacement). Libraries that use browser-only APIs or React state at import time must be wrapped in a Client Component. That last point causes most of the practical friction, so migrate pages that depend on many third-party widgets late.

The planner below shows the first step of a migration as a table. It maps each pages/ file to the app/ file that replaces it and flags a conflict when a route already exists in app/.

Node.js Plan a pages-to-app migration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The conflict on /blog/[slug] is the situation you reach mid-migration: the new page exists, the old one is still there, and the router refuses to guess. Real migrations add one more column to this table: who owns each route, and whether it is finished.

A migration checklist for each route

Use the same short list for every page you move:

  • The app/ page renders the same content and passes the same tests as the old page.
  • Metadata (title, description, Open Graph tags) matches. Compare the page source before and after.
  • Redirects and 404 behavior still work, including for unknown dynamic params.
  • Caching is a conscious choice: static, revalidated or dynamic.
  • Client-only code is isolated in Client Components, and no secret leaks across the boundary (see Keeping Server Code on the Server).
  • The old pages/ file is deleted in the same pull request.

Small pull requests, one route at a time, keep the risk low and let you ship the whole time.

Migrating a Create React App or Vite single-page app

A single-page app (SPA) built with Create React App (CRA, now deprecated) or Vite is a different starting point from a Pages Router project. It has one HTML file, one JavaScript bundle and a client-side router such as React Router. Moving it to Next.js gains you server rendering, per-page code splitting, built-in image and font optimization and a real backend in the same project. As with the Pages Router, you can move in two stages and keep shipping.

Stage 1: run the SPA inside Next.js

The official guidance is to first make the existing app run unchanged inside Next.js as a client-only app, then convert routes one at a time.

  1. Install and clean up. Install next, keep react and react-dom, and remove react-scripts (CRA) or vite and its plugins. Replace the scripts with "dev": "next dev", "build": "next build" and "start": "next start".
  2. Add next.config.ts. For a first step that stays a pure static site, set output: "export" (see Building and Deploying); it produces plain files you can host anywhere, just like the old build output. CRA used a build folder and Vite a dist folder; Next.js writes to out/ for a static export (set distDir to keep a custom name).
  3. Create the root layout. The old public/index.html (CRA) or index.html (Vite) becomes app/layout.tsx. The <html lang> and <body> go there, <title> and meta tags become the metadata export, and the <script> tag for main.jsx disappears: Next.js adds its own. Global CSS imports (index.css) move into the layout.
  4. Add one catch-all page that renders the old app on the client. An optional catch-all route matches every URL, and a client-only wrapper loads the old App component with server rendering turned off:
TSX
// app/[[...slug]]/page.tsx (read-only)
import { ClientOnly } from "./client";

export function generateStaticParams() {
  return [{ slug: [""] }]; // one static entry point; the SPA handles the rest
}

export default function Page() {
  return <ClientOnly />;
}
TSX
// app/[[...slug]]/client.tsx (read-only)
"use client";

import dynamic from "next/dynamic";

const App = dynamic(() => import("../../src/App"), { ssr: false });

export function ClientOnly() {
  return <App />;
}

Why ssr: false? Old SPA code runs window and localStorage code at import time, which crashes on the server. Turning off server rendering for the whole old app avoids that while you migrate. Your React Router keeps working because the browser gets the same app on every URL. Move the old src/ folder next to app/, and keep public/ as it is: Next.js serves it from the site root the same way.

Stage 2: convert it route by route

Now replace the client router with the file-based router, one route at a time (compare File-Based Routing):

React Router Next.js App Router
<Route path="/about" element={<About />} /> app/about/page.tsx
path="/posts/:id" app/posts/[id]/page.tsx
path="*" app/not-found.tsx
Nested routes with <Outlet /> layout.tsx with
<Link to="/about"> <Link href="/about"> from next/link
useNavigate() useRouter() from next/navigation
useParams() useParams() from next/navigation (or the params prop in a page)
useLocation() usePathname() and useSearchParams()
<Navigate to="/login" /> redirect("/login") in a Server Component, or router.push in a client one

Each moved page is a Server Component by default. If it uses useState, useEffect or event handlers, add "use client" at the top (see Client Components and "use client"); that is nearly all of your old components, which is fine for a first pass. After a route works, look for work that can move to the server, such as the useEffect that fetches data on load: make the page an async Server Component and fetch there (Fetching Data in Server Components).

Environment variables, images and other details

  • Environment variables. CRA's REACT_APP_ and Vite's VITE_ prefixes become NEXT_PUBLIC_ for values that the browser may read; Vite's import.meta.env.X becomes process.env.NEXT_PUBLIC_X. Variables without the prefix stay on the server. See Environment Variables.
  • Images. A <img> tag still works. Moving to next/image gives resizing and lazy loading, but it needs a width and height or fill (Images). Importing an image gives you an object with src, width and height in Next.js, not a plain URL string.
  • CSS. Global CSS works as before, but only the root layout may import global files. CSS Modules work the same way.
  • API calls. A dev proxy (proxy in CRA's package.json, server.proxy in Vite) becomes rewrites() in next.config.ts, or you move the endpoints into Route Handlers.
  • Browser-only code. Anything that touches window or document must run in an effect or behind a check, because Client Components are also rendered once on the server.

The stand-in below automates two of the mechanical edits: it renames environment variables and rewrites a few router imports in a piece of source code, and it converts React Router paths to app/ file paths. It is deliberately simple. A real codemod works on syntax trees, but you can see how much of the move is plain renaming.

Node.js Convert env vars, router calls and route paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that useRouter still needs an import from next/navigation and "use client" on top: the stand-in rewrites names but a real migration also needs those two lines, which a good codemod adds for you. Run next build often, because the build catches server-only crashes that the dev server may hide.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the recommended way to upgrade across several Next.js major versions?

    One major at a time keeps each failure tied to a single set of changes, and the official codemods target one jump at a time.
  2. 2. In Next.js 16, what must you do with the params prop of a page?

    params and searchParams are promises. Synchronous access, which only warned in 15, no longer works in 16.
  3. 3. Which Pages Router feature does generateStaticParams replace?

    getStaticPaths listed which dynamic paths to build. generateStaticParams does the same in the App Router.
  4. 4. Both pages/blog/[slug].tsx and app/blog/[slug]/page.tsx exist. What happens?

    Both routers can coexist, but not for the same URL. The error is a useful reminder to delete the old file once the new route works.
  5. 5. Which import should a Client Component inside app/ use to read the current path?

    The app directory uses the hooks in next/navigation. next/router belongs to the Pages Router.

Summary

  • Upgrade on a clean branch, one major version at a time, with the official upgrade command, the codemods, a careful diff review, tests and a build.
  • Next.js 15 made cookies(), headers(), params and searchParams asynchronous and stopped caching fetch and GET handlers by default. Next.js 16 removed synchronous access, made Turbopack the default, renamed middleware to proxy, and introduced Cache Components.
  • Codemods edit code structurally and report what they changed. Review their output and look for comments they leave behind.
  • Pages and App routers can coexist. Migrate leaf routes first, convert data fetching, switch to next/navigation, delete each old file, and do API routes last.
  • A URL cannot exist in both routers. Treat that error as a safety net.

Next: Project: A Markdown Blog