Skip to content

No. 24Next.js8 min read2,173 words

Migrating to the Next.js App Router: a step-by-step guide

A step-by-step guide to migrating a Next.js Pages Router app to the App Router: run both routers side by side, port routes by risk, and avoid the common traps.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01You can migrate to the App Router incrementally: pages/ and app/ run in the same project, so you move one route at a time and ship as you go.
  2. 02A single path cannot exist in both routers. Delete the pages/ file in the same commit that adds the app/ route.
  3. 03Navigating between a Pages Router route and an App Router route is a full page load, so migrate routes that link to each other heavily as a group.
  4. 04getServerSideProps becomes an async Server Component, getStaticPaths becomes generateStaticParams, next/head becomes the metadata export, and API routes become Route Handlers.
  5. 05The real work is deciding the 'use client' boundary. Push it down to the smallest interactive leaf, or you lose the bundle-size benefit you migrated for.
On this page ยท 11

You do not have to migrate a Next.js app to the App Router in one go. The pages/ and app/ directories run side by side in the same project, so the safe approach is to upgrade to the current Next.js version, create a root layout, then move routes one at a time, deleting each old page in the same commit as its replacement. The order you move routes in, and where you draw the client boundary, matter more than any single API change.

This guide is the process we follow when we move a production Next.js app from the Pages Router, including the traps that cost teams the most time.

Should you migrate at all?

If your Pages Router app is fast, stable and easy to change, you can stay. The Pages Router is still supported in Next.js 16, and a forced rewrite is rarely worth the disruption on its own.

The reasons to move are concrete. Server Components fetch data on the server without shipping that code or those queries to the browser. Nested layouts keep shared UI mounted between navigations. Streaming with Suspense sends the page shell before slow data is ready. And new framework features, like Cache Components and Partial Prerendering, are App Router only.

Signal in your appWhat the App Router gives you
Large client bundles, slow interaction on mobileServer Components ship no JavaScript for non-interactive UI
Pages blocked on one slow queryStreaming with Suspense, so the shell renders first
Repeated layout code and getLayout patternsNested layout.tsx files that persist across navigation
Lots of API routes that only exist to feed your own pagesFetch data directly in Server Components, mutate with Server Actions
Mostly static content, rarely changingLess to gain; migrate opportunistically

If several of the first four rows describe you, the migration pays for itself. If only the last one does, there is no rush.

Step zero: upgrade Next.js first

Migrate against the current APIs, or you will port routes twice. Upgrade the app to Next.js 16 while it is still on the Pages Router, using the official upgrade guide and the codemods. The changes that affect a migration most:

  • Node.js 20.9 or newer is required, and TypeScript 5.1 or newer.
  • Request APIs are async only. cookies(), headers(), draftMode(), and params and searchParams in the App Router must be awaited. Synchronous access is removed.
  • Middleware is now Proxy. middleware.ts is deprecated in favour of proxy.ts, which runs on Node.js.
  • Turbopack is the default bundler for next dev and next build. A custom webpack config will fail the build until you migrate it or opt out with --webpack.
  • Removals. serverRuntimeConfig and publicRuntimeConfig are gone (use environment variables), as are AMP support and the next lint command.

Get the upgraded app green in CI and in production before you touch routing. Then every change after that is purely the router migration.

Run both routers at once

This is what makes incremental migration possible. When both directories exist, each path is served by whichever router defines it. You can leave most of the app in pages/ and carve off one route into app/.

Three rules to know before you start:

  1. One path, one router. You cannot have pages/dashboard.tsx and app/dashboard/page.tsx at the same time. The build will fail. Delete the old file in the same commit that adds the new one.
  2. Cross-router navigation is a hard navigation. The migration guide notes that moving between a Pages Router route and an App Router route is a full page load, and next/link will not prefetch across routers. Migrate tightly linked sections (all the settings pages, say) together so users do not feel it.
  3. Shared components need care. A component used by both routers cannot import useRouter from next/router in the App Router. Use the next/compat/router version during the transition, then switch to next/navigation once the component only lives in app/.

A migration order that works

  1. Upgrade to Next.js 16 and stabilise.
  2. Create app/layout.tsx with global CSS and providers.
  3. Port one or two low-traffic, low-risk routes (settings, an about page) to learn the patterns as a team.
  4. Move the data-heavy pages where Server Components pay off the most.
  5. Move API routes that only serve your own UI, often replacing them with Server Components and Server Actions.
  6. Leave routes with complex auth, heavy client state or unusual _app logic until the patterns are familiar.
  7. Delete pages/, _app and _document once the last route is gone.

The root layout replaces _app and _document

In the Pages Router, _app.tsx and _document.tsx wrap everything. In the App Router, that job belongs to app/layout.tsx, which must render the html and body tags itself. It is the first file to create, and it is where global CSS and providers live.

Providers such as a theme context or a query client need browser state, so they must be Client Components. Split them into their own file:

// app/providers.tsx
"use client";
 
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState } from "react";
 
export function Providers({ children }: { children: React.ReactNode }) {
  const [client] = useState(() => new QueryClient());
  return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
}
// app/layout.tsx
import type { Metadata } from "next";
import "./globals.css";
import { Providers } from "./providers";
 
export const metadata: Metadata = { title: "Dashboard" };
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

The layout itself stays a Server Component. Only the provider wrapper opts into the client, and children passed through it can still be Server Components. While both routers exist, providers are mounted separately in _app and in the root layout, so client state in them is not shared across the boundary.

Migration is also a good moment to ask which providers you still need. Many apps carry a global client cache only to hold data that Server Components can now fetch directly. Our guide to React state management covers what usually survives.

Data fetching: the mapping table

This is the change that does the most work, and most of it is mechanical once you see the mapping.

Pages RouterApp Router
getServerSidePropsAn async Server Component that fetches inline
getStaticPropsAn async Server Component whose data is cached (static by default without Cache Components, or "use cache" with them)
getStaticProps with revalidatefetch with next.revalidate, or cacheLife with Cache Components
getStaticPathsgenerateStaticParams
fallback: falseexport const dynamicParams = false (without Cache Components only)
next/headThe metadata export or generateMetadata
pages/api/*Route Handlers in app/**/route.ts, or Server Actions for mutations

getServerSideProps becomes an async component

A page that used getServerSideProps to load data and pass it down as props collapses into an async Server Component:

// pages/orders/[id].tsx (before)
export async function getServerSideProps({ params }) {
  const order = await db.order.findUnique({ where: { id: params.id } });
  if (!order) return { notFound: true };
  return { props: { order } };
}
 
export default function Order({ order }) {
  return <OrderDetail order={order} />;
}
// app/orders/[id]/page.tsx (after)
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { OrderDetail } from "@/components/order-detail";
 
export default async function OrderPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const order = await db.order.findUnique({ where: { id } });
  if (!order) notFound();
 
  return <OrderDetail order={order} />;
}

No props plumbing, no serialization step you control by hand, and the query never reaches the browser. Note that params is a promise in Next.js 16. If the old page checked the session in getServerSideProps, move that check into the data access code, not just the page. We explain why in our guide to Next.js authentication patterns.

getStaticPaths becomes generateStaticParams

// app/blog/[slug]/page.tsx
export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((post) => ({ slug: post.slug }));
}
 
export const dynamicParams = false; // like fallback: false

The generateStaticParams reference covers partial generation and how it interacts with dynamicParams. One caveat: dynamicParams belongs to the previous caching model. With Cache Components enabled, that option is not available, so unknown slugs are handled in the page itself, typically by calling notFound() when the lookup returns nothing.

Decide your caching model up front

Next.js 16 has two caching models. Without Cache Components, routes are prerendered when they can be and become dynamic when they read cookies, headers or search params; you can force behaviour with route segment config like export const dynamic = "force-dynamic". With cacheComponents: true, everything is dynamic by default, you opt into caching with "use cache", and the dynamic, dynamicParams, revalidate and fetchCache segment options are removed altogether. Pick one before you migrate the data-heavy routes so you do not port them twice. Our explainer on Next.js caching compares the two. Where those routes should render is a separate decision, covered in edge vs server rendering.

Hooks and APIs that changed

A lot of migration time goes on small renames. The ones that come up on every project:

  • useRouter comes from next/navigation, not next/router, and no longer returns pathname, query, asPath, locale or isReady. Use usePathname, useSearchParams and useParams in Client Components, or the params and searchParams props in pages.
  • next/head is replaced by the metadata export (static) or generateMetadata (dynamic).
  • Built-in i18n routing from next.config.js does not apply to the App Router. Locales usually become a [lang] dynamic segment plus a redirect in proxy.ts.
  • API routes become Route Handlers that export functions named after HTTP methods and use the Web Request and Response objects.
// app/api/orders/route.ts
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
 
export async function GET() {
  const orders = await db.order.findMany({ take: 50 });
  return NextResponse.json(orders);
}

Before porting an API route, ask whether it still needs to exist. Many only fed data to your own pages, and a Server Component can now read that data directly. Keep Route Handlers for webhooks, public APIs and anything third parties call.

The "use client" boundary is the real work

The renames are easy. The judgement call is deciding which components stay on the server and which need the browser. Anything using useState, useEffect, event handlers or browser-only APIs needs "use client" at the top of its file.

The mistake we see most often is putting "use client" on a whole page because one button needs an onClick. That pulls the page and everything it imports into the client bundle and throws away the main benefit you came for. Push the directive down to the smallest leaf that needs interactivity, and let everything above it stay a Server Component that fetches data and renders HTML.

A practical tell: if a component imports both a database client and useState, it is doing two jobs and needs splitting. The data part stays on the server; the interactive part becomes a small client island that receives data as props. Our mental model for App Router rendering goes deeper on where that line belongs, and data fetching patterns in React Server Components covers how to load data once it is on the server.

Common traps during migration

  • Client-side data fetching left in place. Pages that fetched in useEffect still work, but you get none of the benefits until the fetch moves to the server.
  • Window and document access in shared components. Code that assumed it only ran in the browser now runs during server rendering too.
  • CSS-in-JS libraries without App Router support. Check each one before you start; some need a registry component or a replacement.
  • Non-serializable props. Plain functions and class instances cannot be passed from Server to Client Components. Pass plain data, or a Server Action.
  • Auth checks that lived in getServerSideProps. They do not automatically protect Server Actions or Route Handlers.
  • Accidental dynamic rendering. One cookies() call deep in a shared component can make a page you expected to be static render per request.

Verify every move

After each route moves, run next build and read the route summary. Each route is marked as static, partially prerendered or dynamic, so you can spot pages that became dynamic by accident. Then run your end-to-end tests against the migrated paths, paying particular attention to links that now cross between routers. Catching a regression during migration is far cheaper than catching it as a latency complaint after launch.

The short version

Treat the migration as a series of small, shippable commits, not a rewrite. Upgrade to Next.js 16 first, stand up the root layout, move one quiet route to learn the patterns, then work through the data-heavy pages where Server Components save bundle size and round trips. Keep the client boundary small, delete each old page in the same commit as its replacement, and read the build report after every move.

If you would rather have a team that has done this before plan and run it, App Router migrations are part of our migrations and replatforming work. Tell us about your app and we will map out the safest path.

FAQ ยท 05 questions

Frequently asked questions

Do I have to migrate my Next.js app to the App Router?

No. The Pages Router is still supported in Next.js 16, and a working app that is fast and easy to change does not need a rewrite. Migrate when you want Server Components, nested layouts, streaming or the new caching model, or when new features you need only exist in the App Router.

Can the Pages Router and App Router run in the same Next.js app?

Yes. Both directories can coexist, and each path is served by whichever router defines it. The catches are that one path cannot be defined in both, navigating between the two routers causes a full page load, and shared components that use routing hooks need the compatibility version of useRouter.

How long does an App Router migration take?

It depends far more on the shape of the app than on its size: how much code relies on getServerSideProps, client-side data fetching, custom _app logic and the old router's query object. A small app can move in days, while a large app with complex auth and global client state is better treated as a series of route-by-route releases over several sprints.

What replaces getServerSideProps in the App Router?

An async Server Component. The page component itself awaits the data, for example a database query, and renders it directly. There are no props to pass from a separate function, and the query code never reaches the browser bundle.

Should I upgrade to Next.js 16 before migrating to the App Router?

Usually yes. Upgrading first means you migrate against the current APIs, such as async params and cookies, proxy.ts instead of middleware.ts, and the new caching options, instead of porting routes twice. The official codemods handle most of the mechanical upgrade changes.

Related service

Next.js Development Services

Production Next.js apps and sites, tuned for speed and search.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts