WordPress to Next.js: a guide to migrating or going headless

Published: · Lucas Kleipoedszus
WordPress to Next.js workflow: inventory, export, redirects and revalidation via webhook

This guide covers both routes from WordPress to Next.js: the full migration, after which WordPress is switched off, and headless, where WordPress stays as the editor and Next.js loads content through the REST API. Whether Next.js is the right choice at all is covered in Astro or Next.js?.

The code samples target Next.js 16 with the App Router (tested with 16.4), TypeScript and Node.js 22. Replace https://old-site.com with your domain.

Step 1: inventory the old site

  1. Every URL. Since version 5.5, WordPress publishes a sitemap at /wp-sitemap.xml; Yoast and Rank Math usually use /sitemap_index.xml. Add the pages that get clicks from Search Console.
  2. Content types. Posts, pages, custom post types, categories, tags.
  3. Plugins that do work. For each plugin decide: replace, rebuild or drop.
  4. Media. Back up the wp-content/uploads folder via SFTP or from a backup.

Route A: full migration

Create the project

pnpm create next-app@latest

Export the content

Next.js has no built-in content layer for Markdown. The simplest option is a JSON file that server components import directly. The script fetches every published post through the REST API (at most 100 per request, page count in the X-WP-TotalPages header) and also writes a redirect list.

// export-wordpress.mjs – run: node export-wordpress.mjs https://old-site.com
import { mkdir, writeFile } from "node:fs/promises";

const site = process.argv[2].replace(/\/$/, "");
const fields = "slug,date,modified,link,title,excerpt,content";
// WordPress returns titles and excerpts as HTML with entities such as – or  
const entities = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", ndash: "–", mdash: "—", hellip: "…", rarr: "→" };
const text = (html) =>
  html
    .replace(/<[^>]+>/g, "")
    .replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (match, code) =>
      code[0] === "#" ? String.fromCodePoint(Number(code.slice(1).replace(/^x/i, "0x"))) : (entities[code] ?? match),
    )
    .trim();

const posts = [];
const redirects = {};

for (let page = 1, total = 1; page <= total; page++) {
  const res = await fetch(`${site}/wp-json/wp/v2/posts?per_page=100&page=${page}&_fields=${fields}`);
  if (!res.ok) throw new Error(`WordPress returned ${res.status} on page ${page}`);
  total = Number(res.headers.get("X-WP-TotalPages") ?? 1);

  for (const post of await res.json()) {
    const legacyPath = new URL(post.link).pathname.replace(/\/$/, "");
    posts.push({
      slug: post.slug,
      title: text(post.title.rendered),
      description: text(post.excerpt.rendered),
      html: post.content.rendered.replaceAll(`${site}/wp-content/uploads/`, "/wp-content/uploads/"),
      pubDate: post.date,
      updatedDate: post.modified,
    });
    if (legacyPath !== `/blog/${post.slug}`) redirects[legacyPath] = `/blog/${post.slug}`;
  }
}

await mkdir("content", { recursive: true });
await writeFile("content/posts.json", `${JSON.stringify(posts, null, 2)}\n`);
await writeFile("redirects.json", `${JSON.stringify(redirects, null, 2)}\n`);
console.log(`${posts.length} posts, ${Object.keys(redirects).length} redirects`);

For pages instead of posts, replace /posts with /pages. Rare named entities are left as they are; use a library such as he if you need all of them. Spot-check the result: page builder shortcodes sometimes end up as plain text.

Images

Copy the backed-up wp-content/uploads folder to public/wp-content/uploads. The paths in the exported HTML stay valid. You can switch key images to the next/image component later.

Post page

// app/blog/[slug]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import posts from "@/content/posts.json";

type Props = { params: Promise<{ slug: string }> };

export function generateStaticParams() {
  return posts.map((post) => ({ slug: post.slug }));
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const post = posts.find((p) => p.slug === slug);
  if (!post) return {};
  return {
    title: post.title,
    description: post.description,
    alternates: { canonical: `/blog/${post.slug}` },
  };
}

export default async function Page({ params }: Props) {
  const { slug } = await params;
  const post = posts.find((p) => p.slug === slug);
  if (!post) notFound();
  return (
    <article>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.html }} />
    </article>
  );
}

Since Next.js 15, params is a promise and has to be awaited. For the relative canonical to become a full URL, set metadataBase: new URL("https://old-site.com") in the root layout.

Redirects

// next.config.ts
import type { NextConfig } from "next";
import { readFileSync } from "node:fs";

const legacy: Record<string, string> = JSON.parse(readFileSync("./redirects.json", "utf8"));

const nextConfig: NextConfig = {
  async redirects() {
    return Object.entries(legacy).map(([source, destination]) => ({
      source,
      destination,
      permanent: true,
    }));
  },
};

export default nextConfig;

Keep any existing settings in next.config.ts next to redirects. permanent: true responds with 308. Google treats 308 like 301. The script strips the trailing slash from old URLs because Next.js first redirects /old-post/ to /old-post. That keeps the redirect chain at two hops at most. Old URLs with special characters such as parentheses or colons must be escaped in source, because Next.js reads it as a pattern.

What plugins used to do

  • Sitemap: an app/sitemap.ts file that returns an array of type MetadataRoute.Sitemap generates /sitemap.xml.
  • SEO metadata: Yoast exposes title and description in the REST field yoast_head_json. Add it to fields and take the values from there.
  • Forms: a route handler or a server action receives the data and sends it on.
  • Comments: export old comments as part of the post and switch new ones off, or use an external service.

Route B: headless with WordPress as the editor

WordPress stays where content is written. Next.js loads it through the REST API, keeps it in the data cache and refreshes it as soon as WordPress says so.

Data access

Check first: new projects from create-next-app enable the cacheComponents option in next.config.ts. The samples here use the established caching through fetch with next.revalidate and next.tags, which only applies without cacheComponents. Remove the option for this route. If you want to keep Cache Components, use functions with "use cache" and cacheTag("wordpress") instead; revalidateTag then works the same way.

// lib/wordpress.ts
const WP = process.env.WORDPRESS_API_URL; // e.g. https://cms.old-site.com/wp-json/wp/v2
const cache = { next: { revalidate: 3600, tags: ["wordpress"] } };

export type Post = {
  slug: string;
  title: { rendered: string };
  excerpt: { rendered: string };
  content: { rendered: string };
  modified: string;
};

export async function getPostSlugs(): Promise<Pick<Post, "slug" | "modified">[]> {
  const slugs = [];
  for (let page = 1, total = 1; page <= total; page++) {
    const res = await fetch(`${WP}/posts?per_page=100&page=${page}&_fields=slug,modified`, cache);
    if (!res.ok) throw new Error(`WordPress returned ${res.status}`);
    total = Number(res.headers.get("X-WP-TotalPages") ?? 1);
    slugs.push(...(await res.json()));
  }
  return slugs;
}

export async function getPost(slug: string): Promise<Post | undefined> {
  const res = await fetch(
    `${WP}/posts?slug=${encodeURIComponent(slug)}&_fields=slug,title,excerpt,content,modified`,
    cache,
  );
  if (!res.ok) throw new Error(`WordPress returned ${res.status}`);
  const [post] = await res.json();
  return post;
}

The list deliberately loads only slug and modified: the data cache does not store responses over 2 MB, and 100 full posts exceed that quickly. revalidate: 3600 is the fallback in case a webhook fails.

// app/blog/[slug]/page.tsx
import { notFound } from "next/navigation";
import { getPost, getPostSlugs } from "@/lib/wordpress";

type Props = { params: Promise<{ slug: string }> };

export async function generateStaticParams() {
  return (await getPostSlugs()).map(({ slug }) => ({ slug }));
}

export default async function Page({ params }: Props) {
  const post = await getPost((await params).slug);
  if (!post) notFound();
  return (
    <article>
      <h1 dangerouslySetInnerHTML={{ __html: post.title.rendered }} />
      <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
    </article>
  );
}

dangerouslySetInnerHTML outputs the HTML unchecked. That is acceptable as long as only your own team writes in WordPress. For generateMetadata you need title and excerpt as plain text, without HTML tags and entities.

Refresh the cache on publish

A route handler receives the call from WordPress and marks all data tagged wordpress as stale:

// app/api/revalidate/route.ts
import { revalidateTag } from "next/cache";

export async function POST(request: Request) {
  if (request.headers.get("x-revalidate-secret") !== process.env.REVALIDATE_SECRET) {
    return Response.json({ revalidated: false }, { status: 401 });
  }
  revalidateTag("wordpress", "max");
  return Response.json({ revalidated: true });
}

Since Next.js 16, revalidateTag requires a second argument. With "max", the next request still gets the old version once and the new one loads in the background. If the new version must appear immediately, pass { expire: 0 }.

In WordPress, a must-use plugin calls the endpoint whenever a post is published, updated or unpublished:

<?php
// wp-content/mu-plugins/nextjs-revalidate.php
// In wp-config.php: define('NEXT_REVALIDATE_URL', 'https://old-site.com/api/revalidate');
//                   define('NEXT_REVALIDATE_SECRET', '…');
add_action('transition_post_status', function ($new, $old, $post) {
    if ($new !== 'publish' && $old !== 'publish') {
        return;
    }
    wp_remote_post(NEXT_REVALIDATE_URL, [
        'headers'  => ['x-revalidate-secret' => NEXT_REVALIDATE_SECRET],
        'blocking' => false,
    ]);
}, 10, 3);

Lock WordPress down

  • Move WordPress to its own subdomain, for example cms.old-site.com.
  • Set the WordPress frontend to noindex or redirect it to the new site, otherwise every piece of content exists twice.
  • For previewing drafts, Next.js offers Draft Mode. The REST API only returns drafts with authentication, for example an application password.
  • If you prefer GraphQL, install the WPGraphQL plugin. Caching and revalidation work the same way.

Launch checklist

  1. Every URL from the inventory returns 200 or redirects with 301/308 to the right target.
  2. Titles, descriptions and canonicals match the old site.
  3. The new sitemap is submitted in Search Console.
  4. A test post published in WordPress appears on the new site.
  5. Images load on mobile and none still points to the old domain.
  6. Compare Search Console and analytics weekly against the pre-migration baseline for the first four weeks.

Sources for all code samples: Next.js generateStaticParams, revalidateTag, redirects in Next.js, WordPress REST API: posts, REST API pagination.