WhoBuilt

Incrementally adopt the Next.js App Router

Jun 21, 2023· 16 min· 54K views·Watch on YouTube

Lee Robinson, a developer at Vercel, explains how to incrementally move a Next.js app from the Pages Router to the App Router.

Move simple routes first

A presentational route can move into a new folder in the `app` directory and become routable when its file is named `page.tsx`. In the App Router, it becomes a Server Component by default, so a page that renders only HTML does not need extra client-side JavaScript.

Keep interactivity in client components

A route that uses React state needs the `use client` directive. Components can be colocated with a route, and the directive only needs to appear at the client entry point. A Server Component can also pass server-rendered children into a Client Component, allowing interactive controls and server-rendered UI to work together.

Replace Pages Router APIs

The App Router uses the Metadata API instead of `next/head`: export a `metadata` object for static title and description values, or use `generateMetadata` for dynamic values. For data fetching, replace `getServerSideProps` with an async Server Component that fetches data directly and uses the result without forwarding it through page props.

Choose caching behavior at the fetch

Fetch results are cached statically by default, similar to `getStaticProps`. Set `cache: 'no-store'` to fetch fresh data on each request, or use `revalidate` to refresh cached data periodically, as with Incremental Static Regeneration. Data can also be passed from the Server Component to a Client Component when the UI needs interactivity.

Keep shared files until migration is complete

The `pages` and `app` directories can coexist during migration, so keep `_app` and `_document` while Pages Router routes remain. Once all routes have moved, replace their global styles and document setup with the App Router root layout, which provides the HTML and body tags and supports nested layouts.

Takeaways

  • Start migration with simple, presentational routes, then move interactive routes by adding `use client` where state or effects are used.
  • Keep the page as a Server Component when only a nested control needs client-side state.
  • Use the Metadata API and native async data fetching in the App Router instead of `next/head` and `getServerSideProps`.
  • Set fetch caching based on freshness needs: default static caching, `no-store` for each request, or `revalidate` for periodic updates.
  • Migrate routes gradually; keep `_app` and `_document` until no routes remain in `pages`.

Mentioned in this talk

Search inside this talk

What was claimed 6

Related talks