Next.jsHard
How do you migrate from the Pages Router to the App Router?
Migrate incrementally: both routers work in the same app, so upgrade Next.js first, create a root app/layout.tsx that replaces _app and _document, then move routes one at a time from pages/ to app/, converting data fetching to Server Components, next/router to next/navigation, and API routes to Route Handlers or Server Functions as you go.
Step by step
- Upgrade to the latest Next.js and React (
npx @next/codemod@canary upgrade latest, ornext upgrade), and fix breaking changes (async request APIs,proxy.ts, image defaults). - Root layout: create
app/layout.tsxwith<html>and<body>, global CSS, fonts and providers from_appand_document. Put providers in a"use client"file. - Move one route: copy
pages/about.tsxtoapp/about/page.tsx. Routes inapp/take priority; delete thepages/version once it works. - Data fetching:
getStaticPropsbecomes an async Server Component with"use cache"+cacheLife(orfetchwith caching options).getServerSidePropsbecomes a Server Component readingcookies()/headers()inside<Suspense>.getStaticPathsbecomesgenerateStaticParams.
- Client logic: mark interactive components with
"use client". ReplaceuseRouterfromnext/routerwithuseRouter,usePathnameanduseSearchParamsfromnext/navigation;router.querybecomesuseParamsanduseSearchParams; router events become effects on pathname changes. - Head tags:
next/headbecomes the Metadata API. - Errors and 404:
pages/404.tsxand_errorbecomenot-found.tsx,error.tsxandglobal-error.tsx. - APIs:
pages/apiroutes can stay. Move them toroute.tswhen convenient; form posts can become Server Functions. - Adopt Cache Components last, once routes are on the App Router.
Pitfalls
- Navigating between
pages/andapp/routes is a full page load. - CSS-in-JS needs a registry.
- Libraries using
next/routerneed App Router versions.
Code example
tsx
1// BEFORE: pages/products/[id].tsx2// export const getStaticPaths = async () => ({ paths: [], fallback: "blocking" });3// export const getStaticProps = async ({ params }) => {4// const product = await getProduct(params.id);5// return { props: { product }, revalidate: 3600 };6// };7// export default function Product({ product }) {8// const router = useRouter(); // next/router9// return <><Head><title>{product.name}</title></Head><h1>{product.name}</h1></>;10// }1112// AFTER: app/products/[id]/page.tsx13import type { Metadata } from "next";14import { cacheLife } from "next/cache";1516async function getProduct(id: string) {17 "use cache";18 cacheLife("hours"); // replaces revalidate: 360019 return fetch(`https://api.example.com/products/${id}`).then((r) => r.json());20}2122export async function generateStaticParams() {23 return [{ id: "1" }]; // replaces getStaticPaths24}2526export async function generateMetadata({ params }: PageProps<"/products/[id]">): Promise<Metadata> {27 const { id } = await params;28 return { title: (await getProduct(id)).name }; // replaces next/head29}3031export default async function Product({ params }: PageProps<"/products/[id]">) {32 const { id } = await params;33 const product = await getProduct(id);34 return <h1>{product.name}</h1>;35}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.