Headless WordPress Guide: Step-by-Step for 2026

Build a headless WordPress site step by step: REST or WPGraphQL, Next.js or Astro, draft previews, CORS, ISR caching and sitemaps. Checked 15 Nov 2026.

Five numbered steps for building a headless WordPress site: WordPress and API, Next.js or Astro, draft previews, cache refresh, SEO and sitemap

Headless WordPress development means keeping WordPress as the place where editors write, and building the public site as a separate app that reads that content over the REST API or WPGraphQL. The build has five parts: a locked-down WordPress back end, an API choice, a front end (Next.js or Astro), previews that work for editors, and a way to refresh pages when content changes. This guide walks through each part in order, with code we checked on 15 November 2026.

The URL of this page still says 2025 so that links to it keep working. We rechecked every version number, API path and code sample here on 15 November 2026, against WordPress 7.1.4, WPGraphQL 2.28.0, Next.js 16.4.6 and Astro 7.4.12.

One honest note before we start: most sites do not need this. If your site is a blog or a brochure with a handful of editors, a normal WordPress theme is faster to build and cheaper to run. Headless pays off when a front-end team needs its own stack, when the same content feeds several apps, or when you need full control over how pages render. We cover the trade-offs near the end so you can decide before you write any code.

What does a headless WordPress architecture look like?

Two applications, two deployments, one content source. WordPress runs on its own host (we will call it cms.example.com) and exposes content through an API. The front end runs somewhere else (app.example.com), fetches from that API on the server, and sends finished HTML to visitors.

  • WordPress keeps the editor, media library, users, taxonomies and SEO plugin. Visitors never see its theme.
  • The API layer is either the REST API built into core or the WPGraphQL plugin.
  • The front end is a Node app (Next.js) or a static-first site (Astro) that turns API data into pages.
  • The glue is three small pieces of code: a front-end redirect, a preview link, and a webhook that tells the front end when content changed. We write all three below.

The part people underestimate is the glue. Fetching posts takes an afternoon. Getting Preview to work, getting new posts to appear, and keeping the CMS domain out of Google take the rest of the project.

How do you set up headless WordPress, step by step?

This is the order we build in. Each step is small enough to test on its own before you move on.

Step

What you do

How you know it works

1

Prepare WordPress: pretty permalinks, HTTPS, an application password, a bridge mu-plugin

The REST API answers and a draft returns 401 without login

2

Pick REST or WPGraphQL

One list query and one single-post query return the fields you need

3

Pick the front end (Next.js or Astro) and fetch content on the server

A post page renders with no client-side fetch

4

Add previews

The editor presses Preview and sees the unsaved draft

5

Add CORS rules only if a browser calls WordPress directly

The preflight check in the code box below passes

6

Add cache refresh (ISR tags or a rebuild hook)

Publishing a post changes the live page within a minute

7

Add SEO output and a sitemap on the front-end domain

Canonical, title and sitemap all use the front-end domain

Step 1: How do you prepare the WordPress back end?

Start with the boring settings. The REST API lives at /wp-json/ only when pretty permalinks are on (Settings, Permalinks, anything except Plain). Serve the site over HTTPS: by default core only offers application passwords on sites that use SSL or run in a local environment, per wp_is_application_passwords_supported(). Run a PHP version WordPress.org recommends (8.3 or newer at the time of writing) and keep core current. WordPress 7.1.4, released 28 October 2026, is the current stable release.

Next, test the API by hand before any front-end code exists. Three checks are worth running now and again after every host change:

# checked on 15 Nov 2026
# 1. The REST API answers, and tells you how many pages exist
curl -s -D - -o /dev/null "https://cms.example.com/wp-json/wp/v2/posts?per_page=1&_fields=id" | grep -i "^x-wp-total"

# 2. A browser preflight from your front-end origin gets the right answer
curl -s -D - -o /dev/null -X OPTIONS "https://cms.example.com/wp-json/wp/v2/posts" \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: GET" | grep -i "^access-control"

# 3. An unauthenticated request cannot see a draft (expect 401 or 403)
curl -s -o /dev/null -w "%{http_code}\n" "https://cms.example.com/wp-json/wp/v2/posts/123"

The first returns the total post count and page count headers. The REST handbook caps per_page at 100, so any list you build has to loop over pages. Asking for a page beyond the last one returns a 400 error, not an empty array, which surprises people the first time a loop runs one page too far. The third check matters for privacy: a draft must not be readable without credentials.

Then create an editor account just for the front end and generate an application password for it (Users, Profile, Application Passwords). The front end uses it only for preview requests, so give that account the Editor role, not Administrator. Our guide to WordPress REST API authentication covers the other options and why we pick application passwords for server-to-server calls.

Finally, add a small must-use plugin. It does three jobs: send anyone who lands on the CMS domain to the front end, point the editor’s Preview button at your preview route, and ping the front end when a post changes. Put the two constants in wp-config.php.

<?php
/**
 * Plugin Name: Headless bridge (checked on 15 Nov 2026 against WordPress 7.1)
 */

// wp-config.php: define( 'HEADLESS_FRONTEND_URL', 'https://app.example.com' );
// wp-config.php: define( 'HEADLESS_SECRET', 'a-long-random-string' );

// 1. Send visitors who land on the CMS domain to the real front end.
add_action( 'template_redirect', static function (): void {
	// Core sitemaps are rendered on template_redirect: leave them alone (see the sitemap section).
	if ( get_query_var( 'sitemap' ) || get_query_var( 'sitemap-stylesheet' ) ) {
		return;
	}
	$path = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';
	wp_redirect( esc_url_raw( untrailingslashit( HEADLESS_FRONTEND_URL ) . $path ), 301 );
	exit;
}, 1 );

// 2. Make the editor's Preview button open the front end's draft route.
add_filter( 'preview_post_link', static function ( string $link, WP_Post $post ): string {
	return add_query_arg(
		array(
			'secret' => HEADLESS_SECRET,
			'id'     => $post->ID,
		),
		untrailingslashit( HEADLESS_FRONTEND_URL ) . '/api/draft'
	);
}, 10, 2 );

// 3. Tell the front end to refresh when a post is published, updated, unpublished or trashed.
add_action( 'wp_after_insert_post', static function ( int $post_id, WP_Post $post, bool $update, ?WP_Post $before ): void {
	if ( 'post' !== $post->post_type ) {
		return;
	}
	$was_live = $before && 'publish' === $before->post_status;
	if ( 'publish' !== $post->post_status && ! $was_live ) {
		return;
	}
	wp_remote_post(
		untrailingslashit( HEADLESS_FRONTEND_URL ) . '/api/revalidate',
		array(
			'timeout'  => 5,
			'blocking' => false,
			'headers'  => array(
				'Content-Type'        => 'application/json',
				'x-revalidate-secret' => HEADLESS_SECRET,
			),
			'body'     => wp_json_encode( array( 'slug' => $post->post_name ) ),
		)
	);
}, 10, 4 );

Three details in that code are easy to miss. The redirect skips core sitemap requests because core renders them on template_redirect, which we deal with in the SEO section. The webhook uses wp_after_insert_post rather than transition_post_status because it fires after terms and meta are saved, so the front end never refreshes against half-saved data. And the preview link carries a shared secret, which we come back to in the preview section because it has a cost.

Step 2: REST API or WPGraphQL, which should you use?

Use the REST API unless you have a concrete reason not to. It ships in core, needs no plugin, and the Astro documentation describes it as the built-in way to connect a front end. Choose WPGraphQL when your pages need data from many related objects in one request, or when several front-end teams want a typed schema to code against.

WPGraphQL is a free plugin from the WPGraphQL project. On 15 November 2026 its WordPress.org page showed version 2.28.0 (updated 12 November 2026), 30,000+ active installs, a 4.9 out of 5 rating from 48 reviews, and a requirement of WordPress 6.0 and PHP 7.4. The listing still says tested up to 7.0.8, so expect that number to lag a release behind. Its support forum on WordPress.org is empty (0 threads); the project handles issues on GitHub, which is where you will look when something breaks.

REST API (core)

WPGraphQL (plugin)

Install

Built in

Plugin, version 2.28.0

Query shape

Fixed per route. _fields trims the response, _embed adds related objects

The client names the fields it wants in one request

Schema

Not enforced, so custom fields can return any shape (the WPGraphQL docs make this point)

Strongly typed, with introspection for tooling

Pagination

page and per_page (max 100), totals in X-WP-Total headers

Cursor based: first and after

Caching

Plain GET URLs that any CDN understands

Smart Cache plugin recommends GET requests with network caching

Custom fields

register_rest_field() or meta with show_in_rest

Extra plugins, for example WPGraphQL for ACF 3.2.1

Drafts and previews

Authenticated GET by ID

X-GraphQL-Preview header, added in 2.21.0 (31 August 2026)

Here are the two queries you need to start with WPGraphQL: a paginated list and a single post by slug.

# checked on 15 Nov 2026 against WPGraphQL 2.28.0
query Posts($after: String) {
  posts(first: 20, after: $after) {
    pageInfo { hasNextPage endCursor }
    nodes { databaseId slug title date modified }
  }
}

query PostBySlug($slug: ID!) {
  post(id: $slug, idType: SLUG) { databaseId title content }
}

Smart Cache is the piece to know about if you pick GraphQL. It ships from the WPGraphQL repository on GitHub (version 2.4.1 on 10 November 2026) rather than from WordPress.org, and it tags each response with an X-GraphQL-Keys header so a host or CDN that supports it can purge only what changed. If you do not run on a host with that support, plan to use the same webhook approach we show for REST.

For a deeper look at when a headless setup beats other CMS options at all, see Headless CMS vs WordPress.

What is the best front-end framework for headless WordPress?

There is no single best one. The honest split is by how often content changes and how interactive the pages are. Astro suits content-heavy sites that are mostly read. Next.js suits sites with logged-in areas, heavy interactivity or a team already working in React.

Next.js

Astro

Current version (15 Nov 2026)

16.4.6 (9 Nov 2026), needs Node 20.9 or newer

7.4.12 (13 Nov 2026), needs Node 22.23.4 or newer

Default rendering

Server components, with static output and ISR

Pre-rendered static HTML, with opt-in server rendering per page

Fresh content

On-demand revalidation by tag or path

Rebuild through a host deploy hook, or render on demand with an adapter

Previews

Draft Mode, built in

Server-rendered preview route behind an adapter

Best fit

App-like sites, members areas, large catalogs

Blogs, docs, marketing sites

Two other things you will run into. Faust.js is a Next.js toolkit for WordPress from WP Engine that bundles authentication, previews and template hierarchy. It is active (@faustwp/core 4.1.1 on 3 November 2026, built for Next.js 16.4.2 or newer) and its WordPress plugin, faustwp 1.9.1, has 1,000+ active installs, a much smaller base than WPGraphQL. And Astro 7 moved to Vite 8, so if you copy an older Astro tutorial, run the official upgrade tool before you debug anything else.

Step 3: How do you fetch WordPress content in Next.js?

Fetch on the server, never in the browser. Server-side requests are not subject to CORS, they keep your credentials private, and the HTML that reaches Google already contains the content. The three files below are a complete, minimal slice: a data helper, a post page and an on-demand refresh endpoint. They target the App Router with Cache Components off (the default), where params is a promise and fetch accepts next.tags and next.revalidate.

// lib/wp.ts - checked on 15 Nov 2026 against Next.js 16.4.6 docs
const WP = process.env.WP_URL!; // e.g. https://cms.example.com

export type Post = {
  id: number;
  slug: string;
  date: string;
  modified: string;
  title: { rendered: string };
  excerpt: { rendered: string };
  content: { rendered: string };
  yoast_head_json?: { title?: string; description?: string; canonical?: string };
};

const FIELDS = 'id,slug,date,modified,title,excerpt,content,yoast_head_json';

export async function getPosts(page = 1) {
  const res = await fetch(
    `${WP}/wp-json/wp/v2/posts?per_page=20&page=${page}&_fields=${FIELDS}`,
    { next: { tags: ['posts'], revalidate: 3600 } },
  );
  if (!res.ok) throw new Error(`WordPress returned ${res.status}`);
  return {
    posts: (await res.json()) as Post[],
    totalPages: Number(res.headers.get('x-wp-totalpages') ?? 1),
  };
}

export async function getPost(slug: string): Promise<Post | null> {
  const res = await fetch(
    `${WP}/wp-json/wp/v2/posts?slug=${encodeURIComponent(slug)}&_fields=${FIELDS}`,
    { next: { tags: [`post:${slug}`], revalidate: 3600 } },
  );
  if (!res.ok) throw new Error(`WordPress returned ${res.status}`);
  const [post] = (await res.json()) as Post[];
  return post ?? null;
}

// Drafts need a logged-in user. An application password belongs to one.
export async function getDraftById(id: number): Promise<Post | null> {
  const auth = Buffer.from(
    `${process.env.WP_USER}:${process.env.WP_APP_PASSWORD}`,
  ).toString('base64');
  const res = await fetch(`${WP}/wp-json/wp/v2/posts/${id}?_fields=${FIELDS}`, {
    headers: { Authorization: `Basic ${auth}` },
    cache: 'no-store',
  });
  return res.ok ? ((await res.json()) as Post) : null;
}

Two choices in that helper are on purpose. List pages get the tag posts while each post gets its own post:slug tag, so publishing one article does not mark every post page stale. And _fields keeps each response small, which matters once a list has a few hundred entries.

// lib/secret.ts
import { timingSafeEqual } from 'node:crypto';

export function safeEqual(given: string, expected: string): boolean {
  const a = Buffer.from(given);
  const b = Buffer.from(expected);
  return b.length > 0 && a.length === b.length && timingSafeEqual(a, b);
}
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getPost, getPosts } from '@/lib/wp';

// Pre-build the newest 20. Any other slug renders on its first visit, then stays cached.
export async function generateStaticParams() {
  const { posts } = await getPosts(1);
  return posts.map((post) => ({ slug: post.slug }));
}

export async function generateMetadata(
  { params }: { params: Promise<{ slug: string }> },
): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) return {};
  return {
    title: post.yoast_head_json?.title,
    description: post.yoast_head_json?.description,
    alternates: { canonical: `https://app.example.com/blog/${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>
  );
}

generateStaticParams pre-builds only the newest 20 posts. A slug that was not pre-built renders the first time someone visits and is cached after that, because dynamicParams defaults to true. That is what keeps build time flat on a site with thousands of posts. One caution on dangerouslySetInnerHTML: it is fine for content your own editors write, but if contributors or imports you do not trust can publish, run the HTML through a sanitizer first.

How do you build the same page in Astro?

Astro pre-renders every page at build time, so the loop over API pages happens inside getStaticPaths(). That function runs in its own isolated scope, so it cannot see variables declared elsewhere in the file, which is why the environment variable is read inside it.

---
// src/pages/blog/[slug].astro - checked on 15 Nov 2026 against Astro 7.4.12 docs
export async function getStaticPaths() {
  // getStaticPaths runs in its own scope, so read the env var inside it
  const WP = import.meta.env.WP_URL; // e.g. https://cms.example.com
  const paths = [];
  let page = 1;
  let totalPages = 1;

  do {
    const res = await fetch(
      `${WP}/wp-json/wp/v2/posts?per_page=100&page=${page}&_fields=id,slug,title,content,yoast_head_json`,
    );
    if (!res.ok) throw new Error(`WordPress returned ${res.status} on page ${page}`);
    totalPages = Number(res.headers.get('x-wp-totalpages') ?? 1);
    for (const post of await res.json()) {
      paths.push({ params: { slug: post.slug }, props: { post } });
    }
    page++;
  } while (page <= totalPages);

  return paths;
}

const { post } = Astro.props;
---
<html lang="en">
  <head>
    <title>{post.yoast_head_json?.title}</title>
  </head>
  <body>
    <h1 set:html={post.title.rendered} />
    <article set:html={post.content.rendered} />
  </body>
</html>

A static Astro site does not update itself. When an editor publishes, something has to trigger a new build. Vercel, Netlify and Cloudflare Pages all offer deploy hooks (a secret URL that starts a build when called). Call that URL from the same wp_after_insert_post action shown earlier instead of our revalidate endpoint. If a full rebuild takes too long for your content volume, add an adapter and set export const prerender = false on the pages that must always be fresh.

How do previews work in headless WordPress?

Preview is where headless projects get stuck. Editors press Preview, and WordPress opens a URL on its own domain. In a headless setup that URL has to land on your front end, the front end has to fetch an unpublished post it normally cannot see, and nothing in the cache may get in the way.

The flow we use has four parts, and the code for each is already above:

  1. The mu-plugin rewrites the Preview link to /api/draft?id=123&secret=... on the front end.
  2. The front end checks the secret, confirms the post exists by asking WordPress with the application password, and switches on Draft Mode.
  3. Draft Mode makes Next.js skip every cache for that browser, and sets a __prerender_bypass cookie. Other visitors keep seeing the cached pages.
  4. The preview route fetches the post by ID with credentials, marks the page noindex, and shows it.
// app/api/draft/route.ts
import { draftMode } from 'next/headers';
import { redirect } from 'next/navigation';
import { safeEqual } from '@/lib/secret';
import { getDraftById } from '@/lib/wp';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const id = Number(searchParams.get('id'));
  const secret = searchParams.get('secret') ?? '';

  if (!id || !safeEqual(secret, process.env.HEADLESS_SECRET ?? '')) {
    return new Response('Invalid request', { status: 401 });
  }
  // Confirm WordPress really has this post before switching Draft Mode on.
  if (!(await getDraftById(id))) {
    return new Response('Post not found', { status: 404 });
  }

  (await draftMode()).enable();
  redirect(`/preview/${id}`); // drafts often have no slug yet, so preview by ID
}
// app/preview/[id]/page.tsx
import { draftMode } from 'next/headers';
import { notFound } from 'next/navigation';
import { getDraftById } from '@/lib/wp';

export const metadata = { robots: { index: false, follow: false } };

export default async function Preview({ params }: { params: Promise<{ id: string }> }) {
  if (!(await draftMode()).isEnabled) notFound();

  const { id } = await params;
  const post = await getDraftById(Number(id));
  if (!post) notFound();

  return (
    <article>
      <p>Preview. This page is not public.</p>
      <h1 dangerouslySetInnerHTML={{ __html: post.title.rendered }} />
      <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
    </article>
  );
}

We preview by ID because a draft often has no slug yet: WordPress only fills the slug in when the post is published or the author sets one.

The shared secret in the Preview URL is a real compromise. It travels through the editor’s browser, so it can end up in history or a screenshot. The WPGraphQL docs describe the same pattern as the fallback for people without WordPress accounts. If you need per-user checks, use Faust.js, which authenticates the actual editor, or rotate the secret on a schedule.

With WPGraphQL the idea is the same, but the preview itself is a header. Since version 2.21.0 you send X-GraphQL-Preview: database_id=123 with an authenticated request and the response overlays the newest autosave on the published post. The older asPreview argument still works but is deprecated. WPGraphQL checks that the caller can edit the post, so the request must carry a credential WordPress recognizes, such as an application password.

# checked on 15 Nov 2026 against WPGraphQL 2.28.0
curl -s https://cms.example.com/graphql \
  -H 'Content-Type: application/json' \
  -H "Authorization: Basic $(printf '%s' 'editor:APP-PASSWORD' | base64)" \
  -H 'X-GraphQL-Preview: database_id=123' \
  -d '{"query":"query($id: ID!){ post(id: $id, idType: DATABASE_ID){ title content } }","variables":{"id":123}}'

One limit worth knowing: if a post has no autosave yet, there is nothing to overlay, and you get the post as saved. Saved drafts preview correctly. Unsaved typing needs the editor to have triggered an autosave first.

How do you fix CORS errors with headless WordPress?

First check whether you have a CORS problem at all. CORS only applies to requests made by a browser. When Next.js server components or an Astro build call WordPress, there is no browser involved and no CORS rule to satisfy. If you see a CORS error, some client-side code is calling the API directly.

When you do need browser calls (a search box, a comment form, a logged-in widget), know what core does. In WordPress 7.1, rest_send_cors_headers echoes back whatever origin made the request and allows credentials. That is permissive, and it is the reason a quick test from localhost works with no setup. For production, replace it with an allow-list. Core adds that filter on rest_api_init at priority 10, so your replacement has to run later.

<?php
// mu-plugin, checked on 15 Nov 2026 against WordPress 7.1
add_action(
	'rest_api_init',
	static function (): void {
		// Core adds this filter on rest_api_init at priority 10, so remove it later than that.
		remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );

		add_filter(
			'rest_pre_serve_request',
			static function ( $served ) {
				$allowed = array( 'https://app.example.com', 'http://localhost:3000' );
				$origin  = get_http_origin();

				if ( $origin && in_array( $origin, $allowed, true ) ) {
					header( 'Access-Control-Allow-Origin: ' . $origin );
					header( 'Access-Control-Allow-Methods: GET, OPTIONS' );
				}
				header( 'Vary: Origin', false );

				return $served;
			}
		);
	},
	15
);

You do not need to set Access-Control-Allow-Headers or Access-Control-Expose-Headers yourself. The REST server already sends them: allowed headers include Authorization and X-WP-Nonce, and exposed headers include X-WP-Total and X-WP-TotalPages. Both lists have filters (rest_allowed_cors_headers and rest_exposed_cors_headers) if you need more. Run the preflight check from Step 1 to confirm.

How do caching and ISR keep a headless site fresh?

Incremental Static Regeneration (ISR) means pages are built once, served from cache, and rebuilt in the background when they go stale. In Next.js you control staleness two ways, and you can use both.

  • Time based: revalidate: 3600 in the fetch options. The first visitor after an hour gets the cached page, and a fresh one builds in the background. The docs suggest long windows (an hour, not a second) and on-demand refresh when you need precision.
  • Event based: the webhook from the mu-plugin calls your /api/revalidate route, which marks tagged data stale. The next request serves the old page while the new one builds.
// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';
import { safeEqual } from '@/lib/secret';

export async function POST(request: Request) {
  const secret = request.headers.get('x-revalidate-secret') ?? '';
  if (!safeEqual(secret, process.env.HEADLESS_SECRET ?? '')) {
    return new Response('Unauthorized', { status: 401 });
  }

  const { slug } = (await request.json()) as { slug?: string };
  revalidateTag('posts', 'max'); // lists and archives
  if (slug) revalidateTag(`post:${slug}`, 'max'); // the single post

  return Response.json({ revalidated: true });
}

Next.js 16 changed one detail here. revalidateTag now takes a second argument, and the docs recommend "max", which gives stale-while-revalidate behavior. The one-argument form still runs but is deprecated, and older tutorials still show it. Also note that marking something stale does not rebuild it: a request triggers the rebuild, so a page nobody visits stays stale until someone does.

Cache layers stack, and each one needs a purge path: the Next.js data cache, your host or CDN, and any object cache on the WordPress side. When an update does not show, check them in that order and test the exact path that failed, for example draft to published, not only edit of an already published post. For the WordPress-side layers, see our WordPress performance guide.

Is headless WordPress good for SEO, and what about sitemaps?

It can be as good as any other setup, because Google receives plain HTML either way. It is also easier to get wrong, because a plugin that used to handle SEO now has output you must wire up yourself. Here is the short checklist we run.

  • One domain in the index. The redirect in the mu-plugin sends the CMS domain to the front end with a 301. Check that cms.example.com pages are not indexed once you launch.
  • Take meta from your SEO plugin. Yoast SEO (version 28.8, tested up to 7.1.4) adds yoast_head and yoast_head_json to REST responses, and offers /wp-json/yoast/v1/get_head?url= for any URL. The JSON includes title, description, canonical, robots and schema. Rank Math (1.0.282, tested up to 7.1.4) has a Headless CMS Support setting under Rank Math SEO, General Settings, Others, and then /wp-json/rankmath/v1/getHead?url=.
  • Rewrite canonical URLs. The SEO plugin builds URLs for the domain WordPress thinks it lives on. Set the canonical in your front end to the public domain, as the page code above does, or every page will point Google at the CMS.
  • Keep structured data. If you render the plugin’s schema JSON yourself, check that the URLs inside it use the front-end domain too. Our schema markup guide covers what to include.

For sitemaps, generate them on the front-end domain from the same API data. Core’s wp-sitemap.xml lists WordPress URLs, so left alone it advertises pages on the wrong host. In Astro, the @astrojs/sitemap integration (3.7.5 today) writes sitemap-index.xml at build time once you set site in astro.config.mjs. In Next.js, a sitemap.ts file does the same:

// app/sitemap.ts
import type { MetadataRoute } from 'next';

const WP = process.env.WP_URL!;

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const entries: MetadataRoute.Sitemap = [];
  let page = 1;
  let totalPages = 1;

  do {
    const res = await fetch(
      `${WP}/wp-json/wp/v2/posts?per_page=100&page=${page}&_fields=slug,modified_gmt`,
      { next: { tags: ['posts'] } },
    );
    if (!res.ok) throw new Error(`WordPress returned ${res.status}`);
    totalPages = Number(res.headers.get('x-wp-totalpages') ?? 1);
    for (const post of (await res.json()) as { slug: string; modified_gmt: string }[]) {
      entries.push({
        url: `https://app.example.com/blog/${post.slug}`,
        lastModified: new Date(`${post.modified_gmt}Z`),
      });
    }
    page++;
  } while (page <= totalPages);

  return entries;
}

A sitemap file is limited to 50,000 URLs under the sitemap protocol; Next.js has generateSitemaps for splitting large sets. To stop the CMS publishing its own sitemap, return false from the wp_sitemaps_enabled filter, but only after you have confirmed the front-end sitemap is live and submitted in Search Console.

Where should you host headless WordPress?

You host two things, and they have different needs. WordPress needs PHP, a database and a place for uploads, so any decent WordPress host works. Keep the CMS reachable from the front end and lock down /wp-admin/ to your team if you can. The front end needs a Node runtime (Next.js) or static hosting (Astro), and the hosts most people use are Vercel, Netlify and Cloudflare, which all support deploy hooks.

We do not quote hosting prices here, because plans change month to month. Instead, price the setup by counting what you will run: a WordPress host, a front-end host, build minutes, image processing, and any managed GraphQL cache. If you want to try the whole stack on your own machine before committing to hosts, our Docker setup for WordPress development gets WordPress running locally in a few commands.

Common mistakes people report

These come from open and closed GitHub issues and the official docs, checked on 15 November 2026. We paraphrase them and link each source.

  • Preview shows old content. A Faust.js user reported that pressing Preview a second time showed stale content, and suspected caching (faustjs issue 1933, opened August 2024, closed 26 October 2026). Take away: the preview route must bypass every cache. Next.js Draft Mode does that for the editor’s browser only.
  • Draft queries return null. After a WPGraphQL update, one team found that a draft page requested by URI came back null (WPGraphQL issue 3353, April 2025, closed June 2025). Take away: request previews by database ID, and on 2.21.0 or later use the X-GraphQL-Preview header the docs now recommend.
  • The Preview button opens the wrong place. A user found that Preview sent editors to the site root instead of the preview path after deploying the front end on Netlify (faustjs issue 1531, opened August 2023, closed 26 October 2026). Take away: press Preview from the live editor after every host or domain change, not only on localhost.
  • A published post stays missing from the cache. A WPGraphQL user reported that a post moved from Draft to Published was never purged, because its cached query had no key to match (WPGraphQL issue 4298, opened June 2023, still open on 15 November 2026). Take away: test the draft-to-published path specifically, and keep a webhook as a second purge path.
  • Logged in, but the API says you are not. The REST handbook states that a cookie request without a nonce is treated as unauthenticated, even when you are logged into WordPress, and the WPGraphQL docs require a nonce for cookie requests too. Take away: for server code, use application passwords and skip cookies. See the REST authentication handbook page.

What are the honest trade-offs of going headless?

You gain control over the front end and a clean separation between content and presentation. You pay for it in complexity, and the costs are easy to underestimate.

  • Plugins that print output stop working. Forms, memberships, shop pages and anything built on shortcodes or blocks that render on the front end need a rebuild or an API.
  • Editors lose the true preview. The editor shows WordPress styling, not your React or Astro components. Previews help, but they are never quite the page.
  • Two systems to run. Two deployments, two sets of secrets, two things that can be down. Debugging crosses a network boundary.
  • SEO and analytics are now your job. Redirects, canonicals, schema and sitemaps no longer come with a plugin toggle.
  • Larger sites need a plan from day one. Lists have to paginate, lookups have to avoid one request per row, and the first visit to an uncached page costs more than a warmed one.

We would not go headless for a site that is mostly a blog, has one or two editors and no separate front-end team. We would for a content hub that feeds a site and an app, a catalog with a front end that needs custom behavior, or a team that already ships React or Astro and wants WordPress only for editing. If you are still weighing options, our comparison of headless CMS options and WordPress lays out the alternatives.

Frequently asked questions

What is a headless WordPress site?

It is a WordPress install that only manages content. A separate front-end app reads that content through the REST API or WPGraphQL and renders the pages visitors see. Editors keep the WordPress dashboard they know.

How do I make WordPress headless?

Leave WordPress as it is, expose the content through the REST API or install WPGraphQL, build a front end that fetches from it, and redirect the CMS domain to the front end. Then add previews and a cache refresh webhook, as in the steps above. No special “headless mode” switch exists in core.

Is WPGraphQL still maintained?

Yes. On 15 November 2026 the latest release was 2.28.0, published on 12 November, with 2.27.1 the day before. The project runs on GitHub, and its monorepo also ships Smart Cache (2.4.1) and WPGraphQL for ACF (3.2.1).

Which version of Next.js or Astro should I use?

The current ones. On 15 November 2026 that was Next.js 16.4.6 and Astro 7.4.12. Check the Node requirement first: Astro 7 needs Node 22.23.4 or newer.

Do I need the REST API if I use WPGraphQL?

You still need pretty permalinks and a working WordPress, but your front end can talk only to /graphql. Many sites keep the REST API on as well, because plugins and the block editor use it.

Can I run headless WordPress on Docker?

Yes, and it is a good way to rehearse the setup. Run WordPress and a database in containers, point your front end at it, and test previews locally before you pay for hosts. See our Docker setup guide for the compose file.

How should I test preview and publish flows?

Test four paths on the live domains: edit a published post, save a new draft, publish that draft, and trash a post. Each should change what visitors see within a minute, and the draft should never be reachable without credentials. Re-run the three checks from Step 1 after any change to hosting or caching.

Varun Dubey

Written by

Varun Dubey

Varun Dubey runs Wbcom Designs, the WordPress studio he founded in India in 2009. He has spent sixteen years building on WordPress and BuddyPress, shipping client work and products such as Reign, BuddyX, Jetonomy and MediaVerse, and has been putting Claude and OpenAI workflows into production since 2023. He writes up what the studio learns along the way.

More about Varun

No comments yet