To migrate from Next.js to Astro, create a new Astro project, add React with npx astro add react, copy your components over unchanged, and rewrite each page.tsx as an .astro page that fetches data in its frontmatter and renders React components with a client:* directive only where they need interactivity. Then replace next/image and next/link, move Markdown into content collections, turn API routes into Astro endpoints or actions, and add redirects for any URL that changes.
A Next.js to Astro migration makes the most sense for content-led sites: marketing pages, blogs, docs and catalogues. If most of your app is interactive and shares client state, stay on Next.js; the Astro vs Next.js comparison covers that decision.
Key Takeaways
- React components move over as-is. Pages and layouts are rewritten as
.astrofiles.- Server components become plain Astro frontmatter; client components become islands with
client:*directives.next/imagemaps to<Image />fromastro:assets;next/linkbecomes a plain<a>with optional prefetch.- Route handlers become endpoints in
src/pages/; Server Actions become Astro actions.- Migrate page by page and keep URLs identical, or add redirects, so search rankings carry over.
Concept map: Next.js to Astro
| Next.js (App Router) | Astro |
|---|---|
app/page.tsx |
src/pages/index.astro |
app/blog/[slug]/page.tsx |
src/pages/blog/[slug].astro |
app/layout.tsx |
src/layouts/Layout.astro imported by pages |
| Server component | .astro component, or React component without a directive |
'use client' component |
React component with client:load, client:visible or client:idle |
generateStaticParams() |
getStaticPaths() |
generateMetadata() |
Props passed to a <head> component in the layout |
next/image |
<Image /> / <Picture /> from astro:assets |
next/link |
<a href> plus prefetch |
app/api/x/route.ts |
src/pages/api/x.ts endpoint |
| Server Actions | Actions in src/actions/index.ts |
proxy.ts / middleware.ts |
src/middleware.ts |
next.config.js redirects |
redirects in astro.config.mjs |
public/ |
public/ (same) |
.env with NEXT_PUBLIC_ |
.env with PUBLIC_, or astro:env |
Step 1: Create the Astro project
Start a fresh project next to the old one, so both can run while you migrate:
npm create astro@latest my-site-astro
cd my-site-astro
npx astro add react
If you used Tailwind CSS, add it too with npx astro add tailwind. Copy public/ across unchanged. The folder structure docs explain where everything goes in an Astro project.
Step 2: Copy components
Copy components/ into src/components/. React components render in Astro without changes, with two exceptions to fix as you go:
- Imports from
next/*(next/link,next/image,next/navigation,next/headers) have no Astro equivalent inside React. Replace them with plain elements or props. - Components that rely on context from a provider in
app/layout.tsx(theme, auth, query client) need that provider inside the island, because each island is its own React root.
Path aliases like @/components work if you add them to tsconfig.json:
{
"extends": "astro/tsconfigs/strict",
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "react",
"paths": { "@/*": ["./src/*"] }
}
}
Step 3: Rebuild the root layout
A Next.js root layout:
// app/layout.tsx (Next.js)
import Header from '@/components/Header';
import './globals.css';
export const metadata = { title: 'Acme', description: 'Invoicing for small teams' };
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body><Header />{children}</body>
</html>
);
}
becomes an Astro layout that takes metadata as props:
---
// src/layouts/Layout.astro
import Header from '../components/Header.tsx';
import '../styles/globals.css';
interface Props { title: string; description?: string }
const { title, description = 'Invoicing for small teams' } = Astro.props;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{title}</title>
<meta name="description" content={description} />
<link rel="canonical" href={new URL(Astro.url.pathname, Astro.site)} />
</head>
<body>
<Header />
<slot />
</body>
</html>
Header renders to static HTML. If it has a mobile menu toggle, either add client:load or rewrite the toggle as a small <script>; the island or script guide helps decide.
Step 4: Rewrite pages and data fetching
In the App Router, a server component fetches data with await. In Astro, the same code goes in the frontmatter:
// app/blog/[slug]/page.tsx (Next.js)
export async function generateStaticParams() {
const posts = await getPosts();
return posts.map((p) => ({ slug: p.slug }));
}
export default async function Post({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const post = await getPost(slug);
return <article><h1>{post.title}</h1><div dangerouslySetInnerHTML={{ __html: post.html }} /></article>;
}
---
// src/pages/blog/[slug].astro
import Layout from '../../layouts/Layout.astro';
import { getPosts } from '../../lib/posts';
export async function getStaticPaths() {
const posts = await getPosts();
return posts.map((post) => ({ params: { slug: post.slug }, props: { post } }));
}
const { post } = Astro.props;
---
<Layout title={post.title}>
<article>
<h1>{post.title}</h1>
<Fragment set:html={post.html} />
</article>
</Layout>
Pages that relied on dynamic rendering (cookies, headers, per-request data) need an adapter and export const prerender = false. The Astro SSR guide covers that setup.
Step 5: Move Markdown and MDX into content collections
If you used @next/mdx, Contentlayer or a custom fs reader, replace it with a content collection:
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';
const blog = defineCollection({
loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/blog' }),
schema: z.object({
title: z.string(),
date: z.coerce.date(),
description: z.string(),
}),
});
export const collections = { blog };
Then query with getCollection('blog') and render with render(entry). MDX files can keep importing React components. The content collections guide walks through it.
Step 6: Images and links
Replace next/image with Astro’s <Image />. Local images are imported so Astro knows their dimensions:
---
// src/components/Hero.astro
import { Image } from 'astro:assets';
import hero from '../assets/hero.jpg';
---
<Image src={hero} alt="Dashboard screenshot" width={1200} priority />
Remote images need image.remotePatterns in astro.config.mjs and explicit dimensions. Replace next/link with <a> tags. To keep instant-feeling navigation, enable prefetching with prefetch: true in config, and optionally add <ClientRouter /> for animated transitions.
Inside React components, next/image becomes a plain <img> with width, height, loading="lazy" and decoding="async", or pass an Astro-optimised image URL in from the parent as a prop.
Step 7: API routes, Server Actions and middleware
A route handler:
// app/api/subscribe/route.ts (Next.js)
export async function POST(req: Request) {
const { email } = await req.json();
await addSubscriber(email);
return Response.json({ ok: true });
}
becomes an endpoint with almost the same code:
// src/pages/api/subscribe.ts
import type { APIRoute } from 'astro';
import { addSubscriber } from '../../lib/newsletter';
export const prerender = false;
export const POST: APIRoute = async ({ request }) => {
const { email } = await request.json();
await addSubscriber(email);
return Response.json({ ok: true });
};
Server Actions map to Astro actions defined with defineAction() in src/actions/index.ts, with input validation through Zod. Middleware moves to src/middleware.ts using defineMiddleware(). All of these need an adapter at runtime.
Step 8: Environment variables, redirects and SEO
- Rename
NEXT_PUBLIC_variables toPUBLIC_, or declare them withastro:envfor validation. - Copy
redirects()fromnext.config.jsintoredirectsinastro.config.mjs. The redirects tip covers static and server redirects. - Set
siteinastro.config.mjsand add@astrojs/sitemap. - Recreate
robots.txt, Open Graph tags and JSON-LD thatgenerateMetadata()produced. - Match trailing slash behaviour with
trailingSlashso URLs do not change.
Step 9: Verify before switching DNS
- Crawl the old site and save a list of URLs.
- Build the Astro site and check that every URL returns 200 or redirects correctly.
- Compare titles, descriptions and canonical tags on key pages.
- Run Lighthouse on the same pages in both versions.
- Test forms, search and any island that replaced a client component.
The official Next.js migration guide has more mappings for less common APIs.
What usually needs a rewrite
- Components using
useRouter,usePathnameoruseSearchParamsfromnext/navigation. Pass values in as props from Astro, whereAstro.urlandAstro.paramsare available. - App-wide client state shared across pages. Use nanostores between islands, or keep that part as a separate app.
- Incremental Static Regeneration. Use scheduled rebuilds, on-demand rendering with route caching, or server islands.
- Libraries tied to Next.js, such as
next-authhelpers. Use framework-neutral packages (for example Auth.js core or Better Auth) in middleware.
If the site you are moving is a marketing or SaaS site, starting from a finished Astro design can be faster than porting old components. The Komal technology and SaaS themes are complete Astro 7 projects you can copy your content into.
FAQ
How long does it take to migrate from Next.js to Astro?
For a content site with a few dozen pages, often a few days, because React components move over unchanged and pages are mostly reshaped rather than rewritten. Apps with heavy client state take much longer and may not be good candidates.
Can I use my React components in Astro?
Yes. Run npx astro add react and import them into .astro files. Without a directive they render to static HTML; with client:load or client:visible they hydrate as islands.
What replaces getStaticProps or generateStaticParams in Astro?
getStaticPaths() returns params and props for each static page, and data fetching happens with await in the page’s frontmatter.
Does Astro support Incremental Static Regeneration?
Not under that name. Similar results come from on-demand rendering with route caching, CDN caching with stale-while-revalidate, scheduled rebuilds, or server islands for the parts that change.
Will migrating from Next.js to Astro hurt SEO?
Not if URLs, titles, canonical tags and structured data stay the same or are redirected properly. Faster pages with less JavaScript often help Core Web Vitals.