Headless WordPress with a Next.js frontend means WordPress keeps the editors, the database and the media library, while a Next.js App Router application does all of the public rendering by reading content over the core REST API at /wp-json/wp/v2 or over WPGraphQL. Three decisions carry the whole architecture: which API you read, how the App Router caches what it reads, and how an editor pressing Update reaches that cache. Preview, authentication, media handling and the deploy split all fall out of those three. This is the operator’s version of the pattern — what to build, what breaks for editors on the first morning, and the honest price of giving up the front-end half of the WordPress plugin ecosystem.
What you’ll accomplish
- A Next.js App Router frontend that renders WordPress content from cache, with the WordPress origin reachable only by that frontend and by editors.
- A deliberate REST or WPGraphQL choice, made against your own most-nested page template instead of somebody else’s benchmark.
- On-demand revalidation: an editor’s Update invalidates exactly the affected pages within seconds, with a slow time-based revalidate as the backstop.
- Draft preview that works for editors without a stranger holding the URL being able to read unpublished content.
- Media served through
next/imagefrom the WordPress uploads host, with the remote pattern pinned rather than wildcarded.
Prerequisites
- WordPress 6.x with pretty permalinks enabled. The REST API has been core since 4.7; application passwords have been core since 5.6 and are only offered over HTTPS.
- Next.js 14 or 15 on the App Router (the
app/directory). The Pages Router can do all of this too, but every API named below is an App Router API. Where 14 and 15 differ the text says so: cache defaults, and whetherparamsanddraftMode()are async. - Somewhere to run Node for the frontend: Vercel, a container platform, or your own Node process behind a reverse proxy. If you self-host across more than one instance, read the shared-cache note in step 5 before you go live.
- Administrator access on WordPress, plus the ability to change the web server config or the edge rules in front of it. Locking the origin down is not optional in this design.
- An honest inventory of the plugins whose value is front-end output: forms, sliders, related-post widgets, pop-ups, page builders, anything that renders through
the_contentor enqueues its own scripts. Headless keeps their admin screens and throws away everything they draw; that inventory is the real cost estimate for this project.
How it works
Three separate paths run through a headless pair, and most operational confusion comes from treating them as one.
The read path is the one visitors take. A request reaches the Next.js server, which either serves an already-rendered page from its cache or renders one by calling WordPress. On a warm cache WordPress is not touched at all, which is the entire point: PHP and MySQL stop being in the request path for anonymous traffic.
The publish path runs the other way. When an editor saves, a WordPress hook posts a signed ping to a route handler on the Next.js app, which calls revalidateTag or revalidatePath from next/cache. That drops the cached entry so the next request re-renders against fresh content. Without this the site is only as fresh as its time-based revalidate.
The preview path is separate again. A draft has no public URL by definition, so the editor’s Preview button has to hand the frontend a token, the frontend has to turn that token into a signed cookie via draftMode(), and only then may it fetch unpublished content with credentials — uncached, and never for anyone else.
REST or WPGraphQL
Both read the same posts table. The difference is round trips against a plugin you now own.
The core REST API needs nothing installed. GET /wp-json/wp/v2/posts?slug=hello-world returns a fixed shape: a lot of fields your template never renders, and none of the nested data it does. Author, featured image and terms arrive as _links, so you either make more requests or add _embed, which inflates every listing response. Trim with _fields and you cut bytes, not round trips. This is the classic N+1: one query for the list, then one per post for the things the card actually shows.
WPGraphQL collapses that into a single POST to /graphql returning exactly the fields the page renders, nested author and media included. In exchange you have adopted a plugin into your update, security and compatibility surface, and a schema that shifts whenever your content model does. Query cost becomes your problem too — a deeply nested query is a lot of SQL behind one HTTP request, and unlike REST there is no per-endpoint cache key to reason about from outside.
The practical rule: if your pages are lists and single posts, REST is enough and one fewer plugin is worth real money in operations. If your templates stitch three or four content types into one view, WPGraphQL earns its keep. Either way the cache lives in Next.js, so switching later is a data-layer change rather than a rewrite.
Step-by-step
-
Prove both APIs answer before you write any frontend code. Run these against your WordPress host:
curl -s -o /dev/null -w '%{http_code} %{time_total}s\n' \ 'https://cms.example.com/wp-json/wp/v2/posts?per_page=1'Expected output is
200and a time under a second. If WPGraphQL is a candidate, install it and check the endpoint answers a real query:curl -s https://cms.example.com/graphql \ -H 'Content-Type: application/json' \ -d '{"query":"{ posts(first:1){ nodes { databaseId title } } }"}'Expected output is a JSON object whose top-level key is
data. Run both against the query your busiest template actually needs and compare wall time — that measurement decides the choice. -
Take the WordPress origin off the public web. A headless origin that answers strangers competes with your own frontend for the same queries and widens the attack surface for no editorial gain. Restrict it to the frontend’s egress address and your admin network, and mark it
noindexin case something slips:# cms.example.com — reachable by the frontend and by editors, nobody else. add_header X-Robots-Tag "noindex, nofollow" always; location / { allow 203.0.113.10; # Next.js egress address allow 198.51.100.0/24; # office and VPN range deny all; try_files $uri $uri/ /index.php?$args; }From an address outside those ranges,
curl -s -o /dev/null -w '%{http_code}\n' https://cms.example.com/should print403. If a full block is too blunt for your setup, the narrower move is to keep the REST API reachable but shut down anonymous enumeration of users and content. -
Create an application password for the frontend. In WordPress, go to Users > Profile > Application Passwords, name it after the frontend, and copy the generated value once. Give it to a dedicated user with the smallest role that can read what you need — not your own administrator account. Verify it:
curl -s -u 'nextjs-frontend:abcd EFGH ijkl MNOP qrst UVWX' \ 'https://cms.example.com/wp-json/wp/v2/users/me?context=edit' \ | head -c 80Expected output starts with
{"id":and your user object. A401with codeincorrect_passwordusually means the header never arrived — see troubleshooting. Application passwords are core, need no plugin, and are revocable one at a time from the same screen; JWT plugins buy you short-lived tokens and refresh flows, which is another dependency to own and is worth it only if you have a real reason for expiry. -
Fetch content in a server component and choose the cache on purpose. Next.js 15 does not cache
fetchby default — an unannotated fetch behaves asno-storeand every visitor reaches WordPress. Next.js 14 cached by default. Never rely on either default; state it:// app/blog/[slug]/page.tsx export const revalidate = 3600; async function getPost(slug: string) { const res = await fetch( `${process.env.WP_URL}/wp-json/wp/v2/posts?slug=${encodeURIComponent(slug)}&_embed=1`, { next: { revalidate: 3600, tags: [`post:${slug}`, 'posts'] } } ); if (!res.ok) throw new Error(`WordPress replied ${res.status}`); const [post] = await res.json(); return post ?? null; } export default async function Page({ params }: { params: Promise<{ slug: string }> }) { // Next.js 14: params is a plain object, so drop the await. const { slug } = await params; const post = await getPost(slug); if (!post) return null; return <article dangerouslySetInnerHTML={{ __html: post.content.rendered }} />; }The
tagsarray is the whole point — it is what the publish path will invalidate by name. The hour-longrevalidateis only the backstop for a ping that never arrives. -
Add the revalidation route handler. A route handler under
app/api/gives WordPress somewhere to ping:// app/api/revalidate/route.ts import { revalidateTag, revalidatePath } from 'next/cache'; export async function POST(request: Request) { const secret = request.headers.get('x-wp-revalidate-secret'); if (!secret || secret !== process.env.REVALIDATE_SECRET) { return new Response('forbidden', { status: 403 }); } const { slug, path } = await request.json(); if (slug) revalidateTag(`post:${slug}`); if (path) revalidatePath(path); revalidateTag('posts'); return Response.json({ revalidated: true, at: Date.now() }); }Take the secret from a header rather than a query string so it stays out of access logs. If you self-host across several Node instances, note that each one keeps its own on-disk cache by default: a ping that lands on instance A leaves instance B stale. Point every instance at a shared cache handler in
next.config, or run one instance, or accept that freshness is bounded by the time-based revalidate. -
Fire the ping from WordPress on publish. Use
transition_post_statusrather thansave_postso autosaves and metadata touches do not stampede the frontend. Put this in a small must-use plugin, not in a theme that a redesign will delete:<?php add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) { if ( 'publish' !== $new_status && 'publish' !== $old_status ) { return; // Not a publish, unpublish, or edit of a live post. } if ( wp_is_post_revision( $post->ID ) || wp_is_post_autosave( $post->ID ) ) { return; } wp_remote_post( 'https://example.com/api/revalidate', array( 'headers' => array( 'Content-Type' => 'application/json', 'X-WP-Revalidate-Secret' => NEXT_REVALIDATE_SECRET, ), 'body' => wp_json_encode( array( 'slug' => $post->post_name, 'path' => '/blog/' . $post->post_name, ) ), 'timeout' => 5, 'blocking' => false, ) ); }, 10, 3 );Define
NEXT_REVALIDATE_SECRETinwp-config.php, never in the plugin file.blockingset to false means the editor’s save never waits on the frontend; the trade is that WordPress cannot tell you the ping failed, so the checks in the next section matter. -
Wire draft preview without leaking drafts. Rewrite the preview link so it points at your frontend, then have the frontend verify the token before enabling draft mode:
add_filter( 'preview_post_link', function ( $link, $post ) { return add_query_arg( array( 'secret' => NEXT_PREVIEW_SECRET, 'id' => $post->ID ), 'https://example.com/api/preview' ); }, 10, 2 );// app/api/preview/route.ts import { draftMode } from 'next/headers'; import { redirect } from 'next/navigation'; export async function GET(request: Request) { const { searchParams } = new URL(request.url); if (searchParams.get('secret') !== process.env.PREVIEW_SECRET) { return new Response('invalid token', { status: 401 }); } const id = searchParams.get('id'); if (!id) return new Response('missing id', { status: 400 }); const draft = await draftMode(); // Next.js 14: draftMode() returns directly. draft.enable(); redirect(`/preview/${id}`); }draftMode()sets a signed, HTTP-only cookie and forces every route the visitor then loads to render dynamically. Your preview page must checkisEnabledbefore it fetches anything with credentials, and must fetch withcache: 'no-store'andcontext=editso the draft is never written into a shared cache:// app/preview/[id]/page.tsx import { draftMode } from 'next/headers'; export default async function Preview({ params }: { params: Promise<{ id: string }> }) { const { isEnabled } = await draftMode(); if (!isEnabled) return <p>Preview is not enabled.</p>; const { id } = await params; const auth = Buffer.from( `${process.env.WP_USER}:${process.env.WP_APP_PASSWORD}` ).toString('base64'); const res = await fetch( `${process.env.WP_URL}/wp-json/wp/v2/posts/${id}?context=edit`, { headers: { Authorization: `Basic ${auth}` }, cache: 'no-store' } ); const post = await res.json(); return <article dangerouslySetInnerHTML={{ __html: post.content.raw }} />; }The shared preview secret is the weak spot: anyone who copies a preview URL out of a chat thread keeps working access. Rotate it on a schedule, and prefer a per-post nonce if your editorial workflow involves outside reviewers.
-
Let
next/imageserve WordPress media. Uploads keep living inwp-content/uploadson the WordPress host, so the image optimizer has to be told that host is allowed. Pin the path, not just the domain:// next.config.mjs export default { images: { remotePatterns: [ { protocol: 'https', hostname: 'cms.example.com', pathname: '/wp-content/uploads/**', }, ], }, };If step 2 blocked the origin by IP, the uploads path must stay publicly readable, because the optimizer fetches it server-side but browsers may also hit it directly. Serving uploads from a separate hostname or an object store keeps that hole small and specific.
Validate it works
Confirm the read path caches. Request a page twice and compare timings; the second should be much faster, and on a self-hosted Node server Next.js reports its route cache state in a response header:
curl -s -o /dev/null -w '%{time_total}s\n' https://example.com/blog/hello-world/
curl -sI https://example.com/blog/hello-world/ | grep -i 'x-nextjs-cache\|x-vercel-cache'
Confirm the revalidate endpoint rejects unsigned pings, then accepts a signed one:
curl -s -o /dev/null -w '%{http_code}\n' -X POST https://example.com/api/revalidate \
-H 'Content-Type: application/json' -d '{"slug":"hello-world"}'
# 403
curl -s -X POST https://example.com/api/revalidate \
-H 'Content-Type: application/json' \
-H 'X-WP-Revalidate-Secret: the-secret-from-wp-config' \
-d '{"slug":"hello-world","path":"/blog/hello-world"}'
# {"revalidated":true,"at":1756600000000}
Then do it for real: change a headline in WordPress, click Update, wait five seconds, and check the published page reflects it.
curl -s https://example.com/blog/hello-world/ | grep -o '<h1[^>]*>[^<]*</h1>'
Finally confirm nothing leaks. A draft post ID fetched without the preview cookie must not render, and the origin must refuse strangers:
curl -s -o /dev/null -w '%{http_code}\n' https://example.com/preview/4242
curl -s -o /dev/null -w '%{http_code}\n' https://cms.example.com/wp-json/wp/v2/posts?status=draft
# 401
Troubleshooting
Every visitor reaches WordPress and PHP load never drops. On Next.js 15 an unannotated fetch is not cached, so add next: { revalidate } or cache: 'force-cache' explicitly. Also check whether the route opted itself out: reading cookies(), headers() or searchParams anywhere in the tree makes the whole route dynamic, and one analytics helper deep in a layout is enough to do it.
revalidateTag returns success but the page stays stale. Either the tag string does not match — it is a literal, and post:hello-world is not posts:hello-world — or the ping reached a different instance than the one serving the visitor. Confirm the tag first by calling revalidatePath for the same URL; if that works and the tag does not, it is a naming bug, not an infrastructure one.
The REST API returns 401 with a correct application password. Apache commonly strips the Authorization header before PHP sees it. Set CGIPassAuth On for the WordPress directory, or pass it through explicitly in your rewrite rules. Confirm with a request to /wp-json/wp/v2/users/me — if that fails while an anonymous GET on /posts succeeds, the header is the problem, not the credential. Debugging WordPress REST API errors walks the rest of the response codes.
next/image throws about an unconfigured hostname. The uploads host is missing from images.remotePatterns, or the pattern’s pathname does not match the real upload path — a multisite install serves uploads from /wp-content/uploads/sites/2/, which /wp-content/uploads/** does cover but a narrower pattern will not. Restart the dev server after editing next.config; that file is not hot-reloaded.
Editors say the site is broken and nothing is broken. This is the predictable one. The Preview button behaves differently, the block editor’s in-editor rendering no longer resembles the live page, contact forms show nothing, site search returns nothing, and any plugin that used to inject a banner or a related-posts block now does nothing at all. None of that is a bug. It is the cost of the split, and it needs to be said out loud before launch rather than triaged as incidents afterwards.
When this is the wrong approach
If the site is a brochure with a handful of pages, a well-cached coupled WordPress is faster to build and cheaper to keep. If the editorial team depends on a page builder — Elementor, Divi, Beaver Builder — headless removes the product they were sold, and no frontend work brings it back. If plugins provide the forms, the memberships, the search or the storefront, budget for rebuilding each one in the frontend; a headless WooCommerce storefront in particular is a much larger project than a headless blog and should be decided on its own terms.
If you want the split but not a Node runtime to operate, WordPress with an Astro frontend gets you static output over the same REST API with less to keep running. The reference for both APIs is the WordPress REST API Handbook; the caching and preview behaviour described here is documented in the Next.js App Router documentation.
Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.