惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
C
CERT Recently Published Vulnerability Notes
P
Proofpoint News Feed
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
H
Help Net Security
Recorded Future
Recorded Future
The Register - Security
The Register - Security
F
Full Disclosure
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
Security Archives - TechRepublic
Security Archives - TechRepublic
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
I
InfoQ
T
Tenable Blog
T
Tor Project blog
人人都是产品经理
人人都是产品经理
D
DataBreaches.Net
NISL@THU
NISL@THU
Google DeepMind News
Google DeepMind News
博客园 - 叶小钗
B
Blog
V
V2EX
Jina AI
Jina AI
L
LangChain Blog
月光博客
月光博客
W
WeLiveSecurity
U
Unit 42
AWS News Blog
AWS News Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 聂微东
V
Visual Studio Blog
A
Arctic Wolf
T
Tailwind CSS Blog
The Cloudflare Blog
SecWiki News
SecWiki News
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
宝玉的分享
宝玉的分享
MyScale Blog
MyScale Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Securelist
www.infosecurity-magazine.com
www.infosecurity-magazine.com
腾讯CDC
雷峰网
雷峰网

Clerk Blog

Going to production with Clerk Deploy Clerk Init: The fastest way to start a new project Introducing Clerk CLI Middleware-based route protection bypass Postmortem: Clerk System Outage (March 10, 2026) Clerk for the AI era Add API Key support to your SaaS in minutes Postmortem: Clerk System Outage (February 19, 2026) Using Clerk in a React Native app Postmortem: DNS Provider Outage (February 10, 2026) How do I implement passkeys in Next.js? Clerk ranked #4 fastest-growing software vendor on Ramp’s December 2025 list How do I handle JWT verification in Next.js? Committing to Agent Identity: Clerk raises $50m Series C from Menlo and Anthropic’s Anthology Fund What is the best way to handle authentication in Next.js App Router? Postmortem: Database Incident (September 14–18, 2025) How do I add authentication to a Next.js app? Introducing Free Trials in Clerk Billing Postmortem: August 28, 2025 - elevated API latency and errors Introducing Mosaic: Bring Your Brand to Every Authentication Flow Multi-tenant authentication: What you need to know (and how Clerk helps) What are the risks and challenges of multi-tenancy? Resilience in Practice: Regional Failover at Clerk Build a Cross-Platform B2B App with Clerk, Expo, and Supabase Highlights from the MiduDev/Clerk Hackathon Add multi-tenancy to an app built with Clerk, Lovable, and Supabase How to build an AI coding rules app with Clerk, Lovable, and Supabase How to Build Multi-Tenant Authentication with Clerk Choosing the right SaaS architecture: Multi-Tenant vs. Single-Tenant Postmortem: June 26, 2025 service outage How to Design a Multi-Tenant SaaS Architecture What is multi-tenancy and why it matters for B2B SaaS How OAuth Works Synchronize user data from Clerk to Supabase Add subscriptions to your SaaS with Clerk Billing Getting started with Clerk Billing Multi-tenant analytics with Tinybird and Clerk How Huntr Migrated 250K Users to Clerk: A Scalable Auth Solution for Startups How to take Clerk to Production How to take your Clerk application to production A practical guide to testing Clerk Next.js applications Implementing multi-tenancy into a Supabase app with Clerk How Clerk integrates with a Next.js application using Supabase How Clerk integrates with Supabase Build a blog with tRPC, Prisma, Next.js and Clerk How to enrich PostHog events with Clerk user data How to build a secure project management platform with Next.js, Clerk, and Neon Validate your SaaS idea while building an audience Postmortem: February 6, 2025 service outage Implement Role-Based Access Control in Next.js 15 Build a Next.js sign-up form with React Hook Form Build a Next.js login page template How to implement Google authentication in Next.js 15 What is middleware in Next.js? How to customize Next.js metadata How to set environment variables in Node.js Building a React Login Page Template How to implement per-user OAuth scopes with Clerk Using Clerk SSO to access Google Calendar and other service data Streamline enterprise customer onboarding with SAML and Clerk Clerk launches EASIE SSO and eliminates SSO fees How to secure Liveblocks Rooms with Clerk in Next.js Securing Node.js Express APIs with Clerk and React Combining the benefits of session tokens and JWTs Build a task manager with Next.js, Supabase, and Clerk Comparing Clerk Webhooks vs Backend API Automate Neon schema changes with Drizzle and GitHub Actions A guide to reading authenticated user data from Clerk Role based access control with Clerk Organizations Mitigating OAuth’s recently discovered Open Response Type vulnerability Per-user B2B monetization with Stripe and Clerk Organizations Build a team-based task manager with Next.js, Neon, and Clerk Building a Hybrid Sign-Up/Subscribe Form with Stripe Elements Welcoming Colin from Zod as our inaugural Open Source Fellow Build a modern authenticated chat application with Next.js, Ably, and Clerk Build a waitlist with Clerk user metadata How to use Clerk with PostHog Identify in Next.js How to secure API Gateway using JWT and Lambda Authorizers with Clerk What are passkeys and how do they work? Comparing Authentication in React.js vs. Next.js How to Add an Onboarding Flow for your Application with Clerk Create Your Own Custom User Menu with Radix - Part 2 Introducing Webhook Workflows with Inngest & Svix Clerk raises $30M Series B from CRV and Stripe Clerk in 2023: A Year in Review Build a Movie Emoji Quiz App with Remix, Fauna, and Clerk Ultimate Guide to Magic Link Authentication Create Your Own Custom User Menu with Radix Introducing has(), protect(), and <Protect> Updated Pricing: 10,000 MAUs Free, and a new “Pro Plan” Next.js Authentication with Clerk: Streamlined SSR Handling Clerk Webhooks: Data Sync with Convex Exploring Clerk Metadata with Stripe Webhooks The Ultimate Guide to Next.js Authentication Empower Your Support Team With User Impersonation Clerk Webhooks: Getting Started A Complete Guide to Session Management in Next.js The Advanced Guide to Passwordless Authentication in Next.js How We Roll – Chapter 10: Roundup How We Roll – Chapter 9: Infrastructure
Migrating from Pages Router to App Router: An Incremental Guide
Colin Sidoti · 2023-07-03 · via Clerk Blog

The Next.js App Router (in the /app directory) is a new way to build React applications. If you're already familiar with the Pages Router (in the /pages directory), Next.js has made it really easy to adopt the App Router incrementally, quite literally on a page-by-page basis. This guide explains how.

How is this guide different?

The App Router already has a migration guide, so how is this different?

We want to demonstrate a 1-to-1 mapping of Pages Router to App Router, but this is not a complete migration. In the snippets below you will see obvious potential refactors, and that is on purpose.

As an example, one App Router snippet below still has function called getServerSideProps. It doesn't make sense to keep that name, but we want to demonstrate how getServerSideProps can be expressed in the context of the App Router.

One more disclaimer: this will not explain how to migrate everything. We focused on the best practices for the Pages Router in Next.js 12.3, but left out older APIs like getInitialProps.

One quick clarification

You probably know that the App Router supports both Client Components and the newly introduced Server Components.

Before the App Router, Client Components were just called Components. We want to clarify that after the App Router, absolutely nothing has changed about them.

Most importantly, within the App Router, Client Components are still rendered on the server, then hydrated on client. Search engine crawlers can still index their HTML.

Within this guide, the React code from your Pages Router will be copied to new files and labeled with "use client" at the top. This is expected, since we're doing a 1-to-1 mapping.

Migrating from the Pages Router to the App Router

0. Create the /app directory

Before you can get started with the App Router, you will first need to create a /app directory as a sibling to your /pages directory.

1. Migrate /pages/_document to the App Router

If you have a Custom Document at /pages/_document.tsx, it should look something like this, though likely with some customization:

/pages/_document.tsx

We need to convert this into a Root Layout, which can be treated as a 1-to-1 corollary to a Custom Document:

  1. Clone /pages/_document.tsx into /app/layout.tsx. We will keep both files since we're doing incremental adoption. (If you use .jsx that is no problem, you can use layout.jsx instead)
  2. Remove the next/document import line entirely
  3. Replace <Html> and </Html> with the lowercase, HTML equivalent <html> and </html>. For accessibility, it's best to add a language to your opening tag, like <html lang="en">
  4. Replace <Head> and </Head> with the lowercase, HTML equivalent <head> and </head>. If you only have a self-closing <Head />, you can remove it entirely
  5. Replace <Main /> with {children}, and update the default function export to accept a {children} argument. For Typescript users, children is of type React.ReactNode
  6. Remove <NextScript /> entirely

When complete, /app/layout.tsx should look more like this, plus your customizations:

/app/layout.tsx

Important: /app/layout.tsx is required in the /app directory. If you do not have a Custom Document, you can copy-paste the above sample directly into /app/layout.tsx.

2. Migrate /pages/_app.tsx to the App Router

Note: If you do not have a file at /pages/_app.tsx you can skip to Step 3.

If you have a Custom App at /pages/_app.tsx, it should look something like this, though likely with some customization:

/pages/_app.tsx

The /app directory does not have a 1-to-1 corollary for a Custom App, but it can easily be expressed in the new structure:

  1. Clone /pages/_app.tsx into /app/ClientLayout.tsx. We will keep both files since we're doing incremental adoption. (If you use .jsx that is no problem, you can use ClientLayout.jsx instead)
  2. Add a new line to the top of the file that reads "use client" (with the quotes)
  3. Replace the default export's function signature. Instead of taking Component and pageProps arguments, it should only take a children argument. For Typescript users, children is of type React.ReactNode.
  4. Replace <Component {...pageProps} /> with <>{children}</>, or just {children} if you have another wrapping element
  5. If there are any remaining references to pageProps, please comment them out for now, and revisit them on a page-by-page basis. Next.js has added a new metadata API that should normally be used in place of accessing pageProps here
  6. We recommend changing the default export name from MyApp to ClientLayout. It is not strictly necessary, but it is more conventional

When complete, /app/ClientLayout.tsx should look more like this, plus your customizations:

/app/ClientLayout.tsx

Now, this is where things get a little different:

  • In the Pages Router, /pages/_app.tsx is a "magic" layout file that is automatically added to the React tree
  • In the App Router, the only layout file automatically added to the React tree is the Root Layout from Step 1. So, we will need to manually import and mount our ClientLayout inside /app/layout.tsx

Open /app/layout.tsx, import ClientLayout, and use it to wrap {children}. When complete, your Root Layout should look like this, plus any customizations from Step 1:

/app/layout.tsx

3. Migrate each page to the App Router

Now that your layout has been copied into the App Router, it's time to start migrating your pages one-by-one. There will be a few steps for each page:

  1. Create a directory for the page
  2. Create one file to handle data fetching
  3. Create one file to render the page
  4. Remove the Pages Router page

For the avoidance of doubt: yes, we will be splitting your Pages Router page into two files: one for data fetching and one for rendering.

3.1. Create a directory for the page

Both the Pages Router and the App Router are "filesystem routers," but they are organized slightly differently. In the App Router, each page gets its own directory. Here is how to determine the directory name:

  • If your file is named index.tsx, create the same parent directory structure
    • For /pages/foo/index.tsx, create /app/foo
    • For /pages/index.tsx, you already have /app
  • If your file is not named index.tsx, create a directory with that filename
    • For /pages/bar.tsx, create /app/bar
    • For /pages/baz/[slug].tsx, create /app/baz/[slug]
    • For /pages/baz/[[...slug].tsx, create /app/baz/[[...slug]]

3.2. Create a file to handle data fetching

Inside your page directory, create a file called page.tsx to handle data fetching. Copy-paste the following snippet as the foundation of this file (Note: we will create ClientPage.tsx in 3.3.):

page.tsx

If your Pages Router file does not have any data fetching, you can continue on to the next step. Otherwise, find your data fetcher below to learn how it can be migrated:

Migrating getStaticProps to the App Router

Consider the following is your implementation of getStaticProps:

To migrate this with as little modification as possible, we will:

  1. Copy-paste getStaticProps into page.tsx
  2. Call getStaticProps from within our Page component
  3. Add export const dynamic = "force-static" so the page data is fetched once and cached, not refetched on every load
  4. Pass the result to our (not yet created) ClientPage component

Here is the end result:

page.tsx

Migrating getServerSideProps to the App Router

Consider the following implementation of getServerSideProps:

To migrate this with as little modification as possible, we will:

  1. Copy-paste getServerSideProps into page.tsx
  2. Add export const dynamic = "force-dynamic" so the page data is refetched on every load
  3. Replace any usage of req with the App Router equivalent
  4. Our example uses Clerk for authentication, so the end result will replace this line with its App Router-compatible replacement
  5. Replace req.headers with the new headers() helper
  6. Replace req.cookies with the new cookies() helper
  7. Replace req.url.searchParams with the new searchParams helper
  8. Replace any Dynamic Route segment usage with the new params helper
  9. Call getServerSideProps from within our Page component
  10. Pass the result to our (not yet created) ClientPage component

Here is the end result:

page.tsx

Migrating getStaticPaths to the App Router

Consider the following implementation of getStaticPaths:

In the App Router, this implementation barely changes. It's simply given a new name (generateStaticParams) and the output is transformed to something simpler. That means you can use your old implementation directly, and simply transform the output.

Here is the end result – we included an example of how it can be used in tandem with getStaticProps:

page.tsx

3.3. Create a file to render the page

Now that data fetching is ready, we need to configure the rendering. To accomplish this:

  • Copy your original Pages Router page into ClientPage.tsx
  • Remove any data fetching code, since it now lives in page.tsx

That's it! We have already configured page.tsx to mount this file and pass props, so it should be working.

3.4. Remove the Pages Router page

Now that your page is ready in the App Router, you can delete the old Pages Router variant.

What's next?

Now that your Pages Router application is working in the App Router, it's time to start taking advantage of the App Router and React Server Components.

In particular, right now your ClientPage.tsx files are one big Client Component. Going forward, it's best to refactor this so "use client" is used as sparingly as possible, ideally only on small components. A big Server Component importing many small Client Components will lead to less Javascript sent to the client, and a faster experience for your end user.