TL;DR: Turn on pretty permalinks in WordPress, read posts from the REST API in Next.js with the use cache directive and a cache tag, and build each post page as static HTML. A small must-use plugin in WordPress calls a Next.js route when published content changes, sends previews to a signed preview page, and redirects the old theme so search engines only index the Next.js site.
Originally published on devangwp.com.
In Headless WordPress with Next.js: when it's worth it I ended with four steps: model the content cleanly, build static pages that update on publish, solve previews early, and keep the editor experience first-class. This post is those steps as working code.
It uses the WordPress REST API, so WordPress needs no extra plugins, and Next.js 16.5 with the App Router. The Next.js code builds with no TypeScript or lint errors, and I tested it against the public REST API of WordPress.org News, plus a local stand-in for the publish and preview steps.
What you'll build
WordPress lives on cms.example.com, where editors write. Next.js serves the public site on www.example.com. By the end:
- Every post page is static HTML, built from the REST API.
- Publishing, editing or trashing a post in WordPress refreshes the site, with no redeploy.
- The Preview button in WordPress shows drafts on the Next.js site.
- The old WordPress theme redirects to the Next.js site, so search engines index one copy of each page.
Step 1: Get WordPress ready
Turn on pretty permalinks. Go to Settings, then Permalinks, and pick any option except Plain. With Plain permalinks the /wp-json/ path doesn't exist, and every request has to use ?rest_route=/wp/v2/posts instead.
Check that the API answers:
curl "https://cms.example.com/wp-json/wp/v2/posts?per_page=1&_fields=id,slug,title" You should get a JSON array with one post in it.
Expose your custom content. Posts and pages are in the API already. Custom post types are not: show_in_rest defaults to false, so set 'show_in_rest' => true when you call register_post_type(). For custom fields, ACF (version 5.11 and later) has a Show in REST API setting in each field group's settings, and the values then appear in an acf object on each post. Without ACF, register each field with register_post_meta() and 'show_in_rest' => true, and it appears under meta. For a custom post type, that only happens if the type supports custom-fields.
Add three settings to wp-config.php. The address of the Next.js site, and two secrets that only WordPress and Next.js know:
define( 'HEADLESS_FRONTEND', 'https://www.example.com' ); define( 'HEADLESS_REVALIDATE_SECRET', 'paste-a-long-random-string' ); define( 'HEADLESS_PREVIEW_SECRET', 'paste-a-different-long-random-string' ); openssl rand -hex 32 gives you a good random string. Keep both secrets out of version control.
Step 2: Create the Next.js app
npx create-next-app@latest frontend --yes With the recommended defaults, Next.js 16.5 turns on Cache Components and Partial Prefetching in next.config.ts. The code in this post is written for that setup: data is fetched fresh on every request unless you choose to cache it with "use cache".
Create .env.local with the settings Next.js needs. None of them start with NEXT_PUBLIC_, so they stay on the server and never reach the browser.
WORDPRESS_URL=https://cms.example.com # The same values as in wp-config.php REVALIDATE_SECRET=paste-a-long-random-string PREVIEW_SECRET=paste-a-different-long-random-string # For previews, set up in step 6 WORDPRESS_USER=preview-bot WORDPRESS_APP_PASSWORD="xxxx xxxx xxxx xxxx xxxx xxxx" Then allow featured images from WordPress in next.config.ts, next to the options that are already there:
images: { remotePatterns: [new URL("https://cms.example.com/wp-content/uploads/**")], }, Step 3: Fetch posts from WordPress
All the WordPress code goes in one file, lib/wordpress.ts. If you chose a src folder, put it in src/lib.
import { cacheLife, cacheTag } from "next/cache"; const API = `${process.env.WORDPRESS_URL}/wp-json/wp/v2`; // Ask only for the fields the site uses. With _fields, _embed (for the // featured image) also needs _links or _embedded in the list. const LIST_FIELDS = "id,slug,date_gmt,title,excerpt,_links,_embedded"; const POST_FIELDS = `${LIST_FIELDS},modified_gmt,content`; const EMBED = "_embed=wp:featuredmedia"; export type Post = { id: number; slug: string; date_gmt: string; modified_gmt: string; title: { rendered: string }; excerpt: { rendered: string }; content: { rendered: string }; _embedded?: { "wp:featuredmedia"?: { source_url: string; alt_text: string; media_details?: { width: number; height: number }; }[]; }; }; async function wp(path: string) { const res = await fetch(`${API}/${path}`); if (!res.ok) throw new Error(`WordPress returned ${res.status} for ${path}`); return res; } /** The 20 newest posts, for the blog page. */ export async function getPosts(): Promise<Post[]> { "use cache"; cacheTag("wordpress"); cacheLife("days"); const res = await wp(`posts?per_page=20&${EMBED}&_fields=${LIST_FIELDS}`); return res.json(); } /** WordPress stores non-English slugs percent-encoded ("caf%c3%a9"). */ export function decodeSlug(slug: string) { try { return decodeURIComponent(slug); } catch { return slug; } } /** One published post, or null if there's no post with that slug. */ export async function getPost(slug: string): Promise<Post | null> { "use cache"; cacheTag("wordpress"); cacheLife("days"); const wanted = decodeSlug(slug); const res = await wp(`posts?slug=${encodeURIComponent(wanted)}&${EMBED}&_fields=${POST_FIELDS}`); const [post]: Post[] = await res.json(); // WordPress splits ?slug= on commas and spaces and lowercases it, so // "My-Post,x" would still find "my-post". Only accept an exact match. return post && decodeSlug(post.slug) === wanted ? post : null; } /** Every published post, 100 at a time, for the sitemap. */ export async function getAllPosts(): Promise<Pick<Post, "slug" | "modified_gmt">[]> { "use cache"; cacheTag("wordpress"); cacheLife("days"); const all = []; for (let page = 1, pages = 1; page <= pages; page++) { const res = await wp(`posts?per_page=100&page=${page}&_fields=slug,modified_gmt`); pages = Number(res.headers.get("X-WP-TotalPages") ?? 1); all.push(...(await res.json())); } return all; } const NAMED: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", hellip: "…", }; /** Titles and excerpts arrive as HTML with entities such as ’. */ export function toText(html: string) { return html .replace(/<[^>]*>/g, "") .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))) .replace(/&#x([\da-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16))) .replace(/&([a-z]+);/gi, (m, name) => NAMED[name.toLowerCase()] ?? m) .trim(); } What each piece does:
-
"use cache"stores the function's result, so pages don't call WordPress on every visit. -
cacheTag("wordpress")labels that result, so step 5 can refresh everything from WordPress with one call. -
cacheLife("days")is the safety net. If a publish notification ever goes missing, the next visit after a day still triggers a refresh in the background. -
_fieldskeeps responses small, and_embed=wp:featuredmediaputs the featured image in the same response instead of a second request. -
?slug=always returns an array, even for one post. It's also forgiving: WordPress splits the value on commas and spaces and lowercases it, so/blog/My-Post,xwould still findmy-postand become a duplicate page.getPostonly accepts an exact match, so those addresses get a 404. -
decodeSlugis there because WordPress stores non-English slugs percent-encoded, and in my tests Next.js passed the slug togetPostboth encoded and decoded. Comparing both sides decoded makes/blog/caféwork either way. -
per_pagestops at 100, sogetAllPostsreads theX-WP-TotalPagesheader and asks for each page in turn.
toText is there because WordPress sends titles with typographic entities, such as ’ for a curly apostrophe. In the page body that's fine, because the browser decodes them. In a <title> tag or a meta description, Next.js escapes the text, so the entity would show up as written.
Step 4: Build the blog pages
First, one component that renders a post. The preview page in step 6 uses it too.
// components/article.tsx import Image from "next/image"; import type { Post } from "@/lib/wordpress"; export function Article({ post }: { post: Post }) { const image = post._embedded?.["wp:featuredmedia"]?.[0]; const date = new Date(`${post.date_gmt}Z`); return ( <article> <h1 dangerouslySetInnerHTML={{ __html: post.title.rendered }} /> <time dateTime={date.toISOString()}> {date.toLocaleDateString("en-GB", { dateStyle: "long", timeZone: "UTC" })} </time> {image?.media_details && ( <Image src={image.source_url} alt={image.alt_text} width={image.media_details.width} height={image.media_details.height} sizes="(max-width: 768px) 100vw, 768px" style={{ width: "100%", height: "auto" }} preload /> )} <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} /> </article> ); } Three things worth knowing here:
-
content.renderedis the HTML WordPress produces for the post, the same HTML a theme prints. Rendering it trusts your editors exactly as much as a WordPress theme does. - Set
sizeson the featured image. Without it, every browser downloaded the full 2,560-pixel image when I tested, phones included. Withsizes, phones get a phone-sized file. Images inside the post body load straight from WordPress, not throughnext/image, using thesrcsetWordPress adds to them. -
preloadreplaces thepriorityprop, which Next.js 16 deprecated.
The blog page lists the newest posts:
// app/blog/page.tsx import type { Metadata } from "next"; import Link from "next/link"; import { getPosts, toText } from "@/lib/wordpress"; export const metadata: Metadata = { title: "Blog" }; export default async function BlogPage() { const posts = await getPosts(); return ( <main> <h1>Blog</h1> <ul> {posts.map((post) => ( <li key={post.id}> <Link href={`/blog/${post.slug}`}>{toText(post.title.rendered)}</Link> </li> ))} </ul> </main> ); } And each post gets its own page:
// app/blog/[slug]/page.tsx import type { Metadata } from "next"; import { notFound } from "next/navigation"; import { Article } from "@/components/article"; import { decodeSlug, getPost, getPosts, toText } from "@/lib/wordpress"; // Every post page is static HTML. A post published after the last // deploy is built on its first visit, and that visit waits for it, // so a slug that doesn't exist gets a real 404. export const ensureStatic = "navigation"; export async function generateStaticParams() { const posts = await getPosts(); return posts.map((post) => ({ slug: decodeSlug(post.slug) })); } export async function generateMetadata({ params }: PageProps<"/blog/[slug]">): Promise<Metadata> { const { slug } = await params; const post = await getPost(slug); if (!post) return {}; return { title: toText(post.title.rendered), description: toText(post.excerpt.rendered), alternates: { canonical: `/blog/${post.slug}` }, }; } export default async function PostPage({ params }: PageProps<"/blog/[slug]">) { const { slug } = await params; const post = await getPost(slug); if (!post) notFound(); return ( <main> <Article post={post} /> </main> ); } Why ensureStatic = "navigation": with Cache Components, a post that wasn't built at deploy time can otherwise be sent as a loading shell first, with the content streamed in after. By then the response has already started with a 200 status, so a missing post can't return a 404. With "navigation", the first visit to a new slug waits until the page is built. In my tests, older posts that weren't prebuilt came back complete on their first visit, and a made-up slug returned a real 404 status with a noindex tag.
generateStaticParams must return at least one slug when Cache Components is on, so publish one post before your first build, or the build fails. PageProps is a global type in Next.js 16, so it needs no import.
For the canonical URL to come out as a full address, set metadataBase: new URL("https://www.example.com") in the metadata of app/layout.tsx.
Step 5: Refresh the site when you publish
On the Next.js side, a route that WordPress calls whenever published content changes:
// app/api/revalidate/route.ts import { timingSafeEqual } from "node:crypto"; import { revalidateTag } from "next/cache"; export async function POST(request: Request) { const sent = Buffer.from(request.headers.get("x-revalidate-secret") ?? ""); const secret = Buffer.from(process.env.REVALIDATE_SECRET ?? ""); if (!secret.length || sent.length !== secret.length || !timingSafeEqual(sent, secret)) { return new Response("Unauthorized", { status: 401 }); } revalidateTag("wordpress", "max"); return Response.json({ revalidated: true }); } In Next.js 16, revalidateTag takes a second argument, and the old one-argument form is deprecated. With "max", which the Next.js docs recommend, the cached data is marked as stale. The next visit still gets the old page and starts a rebuild in the background, and the visit after that gets the new one. That's exactly what I saw when testing: one stale response, then the edited title. If something has to disappear right away, such as a post you've pulled for legal reasons, use revalidateTag("wordpress", { expire: 0 }) instead, and the next visit waits for fresh data.
One tag for the whole site keeps things simple: any change refreshes every page that uses WordPress data, and each page rebuilds the next time someone visits it. On a site with thousands of posts, you could tag each post separately as well.
On the WordPress side, create wp-content/mu-plugins/headless.php. Must-use plugins load automatically and can't be switched off from the admin screen, which suits code the site depends on.
<?php /** * Plugin Name: Headless helpers * Description: Connects this WordPress install to the Next.js front end. */ defined( 'ABSPATH' ) || exit; /** * 1. Tell Next.js when published content changes. * This hook runs after the post, its terms and its meta are saved. */ add_action( 'wp_after_insert_post', function ( $post_id, $post, $update, $post_before ) { if ( ! is_post_type_viewable( $post->post_type ) ) { return; // Menus, revisions and other internal types. } $was_live = $post_before && 'publish' === $post_before->post_status; if ( 'publish' !== $post->post_status && ! $was_live ) { return; // A draft changed, so the live site is the same. } wp_remote_post( HEADLESS_FRONTEND . '/api/revalidate', array( 'blocking' => false, 'timeout' => 3, 'headers' => array( 'x-revalidate-secret' => HEADLESS_REVALIDATE_SECRET ), ) ); }, 10, 4 ); Why wp_after_insert_post (WordPress 5.6 and later) and not s...