Headless WordPress with Next.js: how it works and when to use it
Editors keep WordPress; visitors get a fast Next.js front end that reads content through the API. How it fits together, the code, and what you give up.
By Sohail Hussain21 November 20265 min read
In a headless WordPress setup, editors keep using the WordPress admin exactly as before, but visitors never load a WordPress page. A separate Next.js site fetches the content through WordPress's REST API (or GraphQL), pre-renders the pages, and refreshes them when an editor publishes. You get Next.js speed and a smaller attack surface, and your team keeps an editor they know. The price is two systems to host and maintain, and rebuilding everything a WordPress theme and its plugins used to do on the front end: previews, forms, SEO tags, sitemaps, redirects and search.
It is a good fit for content-heavy sites where speed matters and a developer is available long term. It is a poor fit for small sites, sites built in a page builder, and sites that rely on front-end plugins.
How does headless WordPress work?
Two applications, each doing one job:
| WordPress | Next.js | |
|---|---|---|
| Who uses it | Editors | Visitors |
| What it does | Stores and edits content | Fetches content and renders pages |
| Where it lives | A private or separate address, such as cms.example.com | Your main domain |
| What it runs | PHP and MySQL, as usual | Pre-rendered pages, refreshed as content changes |
| Updates needed | Core, plugins, PHP | Next.js and its dependencies |
The link between them is the API. WordPress serves content as JSON at addresses such as /wp-json/wp/v2/posts, documented in the REST API handbook. Next.js requests that JSON when it builds a page, caches the result, and asks again when told content has changed.
The REST API is built into WordPress and covers posts, pages, custom post types and media. The alternative is WPGraphQL, a plugin that lets the front end request exactly the fields it needs in one query. It helps on pages that combine many related items; for most company sites the REST API is enough, and it is what the examples below use.
We build headless WordPress sites as part of our website design and development work, alongside plain WordPress and plain Next.js. In practice, we recommend headless less often than clients expect.
When is headless worth it, and when is it not?
Worth it when the site is large and content-led (a publisher, a big knowledge base, a multi-brand company site), when speed and Core Web Vitals affect revenue, when the same content feeds a website and an app, or when you are moving a WordPress site to Next.js and editors refuse to change tools.
Not worth it when:
- The site is a dozen pages. A well-built standard WordPress site is fast enough and costs much less to run.
- Pages are built in Elementor or another page builder. Their layouts do not survive the trip through the API in any useful form.
- The site relies on front-end plugins: form builders, booking widgets, WooCommerce checkout, membership areas. Each one must be rebuilt.
- Nobody will maintain the Next.js side. Two systems need twice the care.
Next.js vs WordPress and headless CMS vs WordPress cover the wider choice. Sometimes a dedicated headless CMS is a better editor than WordPress for this setup.
How do you fetch WordPress content in Next.js?
Start in WordPress. Put it on its own address, such as a cms subdomain, and stop its theme from serving public pages, for example by redirecting front-end requests to the main site, so search engines do not index two copies of every page. Posts and pages are in the REST API by default. Custom post types appear only if they are registered with show_in_rest set to true, and custom fields need their own REST setting; see custom post types and Advanced Custom Fields.
In Next.js with the App Router, keep the fetching in one small module. Each request is cached for an hour and tagged, so it can be refreshed on demand:
// lib/wordpress.ts
const WP_URL = process.env.WORDPRESS_URL; // e.g. https://cms.example.com
export async function getPosts() {
const res = await fetch(`${WP_URL}/wp-json/wp/v2/posts?per_page=20`, {
next: { revalidate: 3600, tags: ["wordpress"] },
});
if (!res.ok) throw new Error(`WordPress returned ${res.status}`);
return res.json();
}
export async function getPost(slug: string) {
const res = await fetch(
`${WP_URL}/wp-json/wp/v2/posts?slug=${encodeURIComponent(slug)}`,
{ next: { revalidate: 3600, tags: ["wordpress"] } },
);
if (!res.ok) throw new Error(`WordPress returned ${res.status}`);
const posts = await res.json();
return posts[0] ?? null;
}
Then a page that pre-renders the latest posts at build time and renders any others on their first request:
// app/blog/[slug]/page.tsx
import { notFound } from "next/navigation";
import { getPost, getPosts } from "@/lib/wordpress";
export async function generateStaticParams() {
const posts = await getPosts();
return posts.map((post: { slug: string }) => ({ slug: post.slug }));
}
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const post = await getPost(slug);
if (!post) notFound();
return (
<article>
<h1 dangerouslySetInnerHTML={{ __html: post.title.rendered }} />
<div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
</article>
);
}
The rendered fields contain HTML produced by WordPress, so only render content from a WordPress installation you control. Paste a sample API response into our JSON to TypeScript converter to get types instead of the loose ones above.
This uses Next.js's standard caching model, described in its ISR guide. If your project turns on Cache Components, the same idea is written with 'use cache', cacheLife and cacheTag instead.
How do pages update when editors publish?
Waiting an hour for the cache to expire is not acceptable to most editors. Instead, WordPress tells Next.js when content changes. On the Next.js side, a route handler checks a shared secret and revalidates the tag:
// 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({ ok: false }, { status: 401 });
}
revalidateTag("wordpress", "max");
return Response.json({ ok: true });
}
On the WordPress side, a small must-use plugin calls that route whenever a post is saved, skipping autosaves and revisions. REVALIDATE_SECRET is a constant you define in wp-config.php:
<?php
add_action( 'save_post', function ( $post_id ) {
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
return;
}
wp_remote_post( 'https://www.example.com/api/revalidate', array(
'headers' => array( 'x-revalidate-secret' => REVALIDATE_SECRET ),
'timeout' => 5,
) );
} );
With the "max" profile, the next visitor after a publish still gets the old page while the new one builds in the background, and everyone after that gets the update. If editors need to see changes on the very next load, pass { expire: 0 } instead of "max".
What do you lose when WordPress stops rendering the front end?
Everything a theme or plugin did in the browser. Each item has to be rebuilt in Next.js:
- Previews. The Preview button needs Next.js Draft Mode and a preview route that fetches drafts with authentication.
- SEO metadata. Titles, descriptions and Open Graph tags from your SEO plugin must be read from the API and output with Next.js metadata. Some SEO plugins include their tags in REST responses, which helps.
- Sitemaps and redirects. Generate the sitemap in Next.js, and move redirects from the WordPress plugin into Next.js config or a data file.
- Forms. Post to a Next.js route handler or a form service; front-end form plugins will not render.
- Search, menus and comments. Each needs an API call and a component.
None of this is hard on its own. Together, it is why a headless build costs noticeably more than a standard WordPress site, and why running two systems needs a budget for both. If you are moving from WordPress to Next.js entirely, how to move from WordPress to Next.js covers that path. Why we build company websites with Next.js and WordPress for business websites explain when each platform suits a company site on its own.
Was this guide useful?