Lesson 19 of 27Full-stack
The Pages Router and Migrating to App Router
Read and change Pages Router code with confidence, map each pattern to its App Router equivalent, and migrate a real app route by route.
On your first day at a new job you open the main web app and there is no app/ folder. There is pages/, a _app.tsx with nine nested providers, getServerSideProps on half the pages and an api/ folder with forty endpoints. This is normal. Most Next.js apps written before 2023 use the Pages Router, and many of them are still in production and still earning money. You need to be able to fix bugs in it this week, and you may be asked to plan its migration to the App Router this quarter. This lesson teaches you to read Pages Router code fluently, map every pattern to the App Router you already know, and migrate incrementally without a big-bang rewrite.
The Pages Router in one picture
The history in What is Next.js? explained why there are two routers. In the Pages Router, every file in pages/ is a route, and every page is a normal React component that is rendered on the server and then hydrated in full in the browser. There are no Server Components: the whole page component and everything it imports ships as JavaScript. Data reaches the page through special exported functions that run only on the server and return props.
- pages/
- _app.tsxwraps every page: global CSS, providers, layouts
- _document.tsxthe HTML shell: <html>, <body>, server-only
- index.tsx/
- 404.tsxcustom not-found page
- blog/
- index.tsx/blog
- [slug].tsx/blog/:slug, getStaticProps + getStaticPaths
- account/
- settings.tsx/account/settings, getServerSideProps
- api/
- orders/
- [id].ts/api/orders/:id, an API route
- components/
- lib/
- public/
_app.tsx is a component that wraps every page. It is where global CSS is imported, where context providers (theme, auth session, React Query client) live, and where shared layout is applied. Because it wraps everything, it stays mounted as you navigate, so state in it persists.
import type { AppProps } from "next/app";
import { SessionProvider } from "next-auth/react";
import "../styles/globals.css";
export default function App({ Component, pageProps }: AppProps) {
return (
<SessionProvider session={pageProps.session}>
<Component {...pageProps} />
</SessionProvider>
);
}There are no nested layouts. The common workaround is the getLayout pattern: each page attaches a static getLayout function, and _app calls it. If you see Page.getLayout = (page) => <DashboardLayout>{page}</DashboardLayout>, that is what it is doing.
_document.tsx customises the <html> and <body> tags. It renders only on the server, so event handlers and state do nothing there. Add lang, fonts and a few attributes, nothing more.
Data fetching: three functions
Each page chooses its rendering strategy by which function it exports. These are the four classic strategies from Rendering Strategies, expressed as code.
getServerSideProps runs on every request. It receives the request context and returns props, a redirect or a 404:
import type { GetServerSideProps, InferGetServerSidePropsType } from "next";
import { getSession } from "@/lib/auth";
import { getUserSettings } from "@/lib/settings";
export const getServerSideProps = (async ({ req, query }) => {
const session = await getSession(req);
if (!session) {
return { redirect: { destination: "/login?next=/account/settings", permanent: false } };
}
const settings = await getUserSettings(session.userId);
if (!settings) return { notFound: true };
return { props: { settings, tab: typeof query.tab === "string" ? query.tab : "profile" } };
}) satisfies GetServerSideProps;
export default function Settings({ settings, tab }: InferGetServerSidePropsType<typeof getServerSideProps>) {
return <SettingsForm initial={settings} tab={tab} />;
}getStaticProps runs at build time. Add revalidate and the page becomes ISR: served from cache, regenerated in the background at most once per interval. getStaticPaths lists which dynamic paths to build, and fallback decides what happens to the rest:
import type { GetStaticPaths, GetStaticProps } from "next";
export const getStaticPaths: GetStaticPaths = async () => {
const top = await getPopularSlugs(100);
return { paths: top.map((slug) => ({ params: { slug } })), fallback: "blocking" };
};
export const getStaticProps: GetStaticProps = async ({ params }) => {
const post = await getPost(String(params?.slug));
if (!post) return { notFound: true };
return { props: { post }, revalidate: 300 }; // regenerate at most every 5 minutes
};fallback | A path not built at build time... |
|---|---|
false | returns 404 |
true | serves a fallback version of the page immediately (router.isFallback is true, props are empty), then fills it in |
"blocking" | is server-rendered on first request like SSR, then cached as static |
On-demand ISR is done from an API route with await res.revalidate("/blog/my-post"), usually triggered by a CMS webhook. You will also meet getInitialProps, the oldest API. It runs on the server for the first load and in the browser on client navigations, and adding it to _app disables automatic static optimisation for every page without getStaticProps. Treat it as legacy and do not add new uses.
Props are JSON
Whatever these functions return as props is serialised to JSON and embedded in the HTML in a <script id="__NEXT_DATA__"> tag, so the browser can hydrate with the same data. Two consequences matter at work.
First, every prop is public. If getServerSideProps returns a whole user row including passwordHash and the component only shows the name, the hash is still in the page source. This is the Pages Router version of the DTO rule from Server and Client Components: return only what the page renders.
Second, props must be plain JSON. undefined and Date objects fail with errors like "undefined cannot be serialized as JSON. Please use null or omit this value."
Press Run (⌘ Enter) to see what happens.The App Router's RSC payload is more capable: it can send Date, Map, Set, BigInt and even promises to Client Components. So the serialisation errors disappear during migration, but the "every prop is public" rule does not.
What does this print?
const props = { title: "Hi", subtitle: undefined, views: 10 };
console.log(JSON.stringify(props));API routes
pages/api/* files are Node-style request handlers with req and res objects, similar to Express:
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).setHeader("Allow", "GET").end();
const order = await getOrder(String(req.query.id));
if (!order) return res.status(404).json({ error: "Not found" });
res.status(200).json(order);
}One default export handles every method, req.query merges dynamic segments and the query string, and the body is parsed for you (configurable through export const config = { api: { bodyParser: false } }, which webhook handlers use to read the raw body). Route Handlers in the App Router replace these with one exported function per method, using web-standard Request and Response, as you saw in Route Handlers. API routes still work in Next.js 16, so you do not have to migrate them first.
Client-side data: SWR and TanStack Query
Pages Router apps often fetch on the client for anything user-specific or frequently changing: useSWR("/api/me") or useQuery({ queryKey: ["orders"], queryFn }). Some hydrate the cache from getServerSideProps so the first render has data.
In the App Router most of that becomes a Server Component that awaits the data directly, with no loading spinner, no API route and no client JavaScript. Keep a client data library for what is genuinely client-driven: polling, infinite scroll, optimistic UI on a list, data that changes while the user watches. When you keep TanStack Query, prefetch on the server and pass the cache down with its hydration boundary, or pass a promise from a Server Component and read it with use() in the Client Component.
Mapping Pages Router to App Router
Match each Pages Router feature to its App Router equivalent.
A few more you will need while migrating:
| Pages Router | App Router |
|---|---|
import { useRouter } from "next/router" | useRouter, usePathname, useSearchParams, useParams from next/navigation |
router.query | params and searchParams props (Promises) or useParams / useSearchParams |
router.events.on("routeChangeStart") | usePathname + useSearchParams in an effect, or onRouterTransitionStart in instrumentation-client.ts |
pages/404.tsx, pages/_error.tsx | not-found.tsx, error.tsx, global-error.tsx |
getLayout pattern | nested layout.tsx files |
i18n in next.config | app/[lang] segment and proxy-based locale detection |
res.revalidate(path) | revalidatePath / revalidateTag / updateTag |
Migrating incrementally
The app/ and pages/ directories are designed to run side by side in one app. That means you can migrate one route at a time and ship after each one. Do not plan a rewrite branch that lives for six months.
Rules of the road while both routers exist:
- A route lives in one router.
app/about/page.tsxandpages/about.tsxcannot both exist; the build fails with "Conflicting app and page file". Moving a route means deleting its old file in the same pull request. - Navigation between routers is a hard navigation. A
<Link>from a Pages route to an App route does a full page load, with no prefetching across the boundary, and state in_appis lost. Group migrations so users move within one router for common journeys (for example, migrate the whole dashboard section together). - Shared chrome is duplicated for a while. The header and footer are rendered by
_appfor old routes and byapp/layout.tsxfor new ones. Make them plain shared components used by both, so they do not drift. - Shared components need care. A component used by both routers cannot import
next/routerin App routes. UseuseRouterfromnext/compat/router, which returnsnullunder the App Router, or split the component.
Order a sensible incremental migration of a large Pages Router app.
- Tap the steps below in the right order.
Common migration bugs
"window is not defined" or "createContext only works in Client Components". In pages/, every component ran in the browser too. In app/, components are Server Components by default. Libraries that touch window, use hooks or create context need a "use client" boundary. The usual fix for providers is a single app/providers.tsx with "use client" that wraps children, rendered from the root layout.
router.query is undefined. The next/navigation router has no query, asPath, isReady or isFallback. Dynamic params and search params are separate, and in Server Components they arrive as Promises you must await.
next/head does nothing. Titles and meta tags move to export const metadata or generateMetadata.
Auth checks disappear. In the Pages Router, the redirect for signed-out users often lived in getServerSideProps. When a page becomes a Server Component, that check must move to the data access layer or the page itself; it does not come along automatically. Review this explicitly for every migrated route.
Caching surprises. getServerSideProps was always dynamic and getStaticProps always static. In the App Router with Cache Components, a route is dynamic by default and you opt into caching with use cache. A page that was ISR needs use cache and a cacheLife profile, or it will start rendering on every request and your database load jumps.
Global CSS and CSS-in-JS. CSS Modules and Tailwind move across unchanged. Runtime CSS-in-JS libraries need their App Router integration (a style registry in a Client Component) and only style Client Components.
Codemods (npx @next/codemod) handle many mechanical upgrades between versions, such as async request APIs. They do not migrate routers for you, but they keep the version-upgrade step small.
- Pages Router
- The original Next.js router in
pages/: every page is a fully hydrated React component, with data fromgetServerSidePropsorgetStaticProps. - getServerSideProps
- A Pages Router export that runs on every request and returns props, a redirect or
notFound. - getStaticProps
- A Pages Router export that runs at build time; with
revalidateit gives Incremental Static Regeneration. - fallback
- The
getStaticPathsoption that decides what happens to unbuilt paths:false(404),true(fallback page) or"blocking"(render on first request). - __NEXT_DATA__
- The JSON script tag in Pages Router HTML that holds every page prop for hydration. Anything returned as a prop is visible in it.
- hard navigation
- A full page load instead of a client-side transition. It happens when navigating between Pages Router and App Router routes.
- next/compat/router
- A
useRouterfor components shared by both routers; it returnsnullunder the App Router.