DEV Community

Cover image for How to set up headless WordPress with Next.js, step by step
Devang Patel
Devang Patel

Posted on Originally published at devangwp.com AI-assisted

How to set up headless WordPress with Next.js, step by step

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"
Enter fullscreen mode Exit fullscreen mode

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' );
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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/**")],
},
Enter fullscreen mode Exit fullscreen mode

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 &#8217;. */
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();
}
Enter fullscreen mode Exit fullscreen mode

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.
  • _fields keeps responses small, and _embed=wp:featuredmedia puts 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,x would still find my-post and become a duplicate page. getPost only accepts an exact match, so those addresses get a 404.
  • decodeSlug is there because WordPress stores non-English slugs percent-encoded, and in my tests Next.js passed the slug to getPost both encoded and decoded. Comparing both sides decoded makes /blog/café work either way.
  • per_page stops at 100, so getAllPosts reads the X-WP-TotalPages header and asks for each page in turn.

toText is there because WordPress sends titles with typographic entities, such as &#8217; 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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Three things worth knowing here:

  • content.rendered is 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 sizes on the featured image. Without it, every browser downloaded the full 2,560-pixel image when I tested, phones included. With sizes, phones get a phone-sized file. Images inside the post body load straight from WordPress, not through next/image, using the srcset WordPress adds to them.
  • preload replaces the priority prop, 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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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 });
}
Enter fullscreen mode Exit fullscreen mode

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 );
Enter fullscreen mode Exit fullscreen mode

Why wp_after_insert_post (WordPress 5.6 and later) and not save_post: when you save in the block editor, WordPress stores the post first and its terms and custom fields afterwards. wp_after_insert_post runs once all of that is saved, so Next.js never rebuilds a page from half-saved data.

The status check covers publishing, editing a live post, unpublishing and trashing, and skips drafts, which can't change the public site. 'blocking' => false tells WordPress it doesn't need the reply. Depending on how the server makes HTTP requests, WordPress may still wait for Next.js to answer, so the timeout caps that wait at three seconds if the site is down. revalidateTag only marks data as stale, so the route itself answers quickly.

Step 6: Preview drafts

Drafts are the part teams underestimate. Draft Mode in Next.js turns off the cache and sends the editor to the page's normal address. A WordPress draft usually has no slug yet, so there's no normal address to send them to, and the REST API only returns a draft to a logged-in user who is allowed to edit it. A separate preview page that fetches the draft by its ID fits WordPress better.

Create a user for previews. Make a WordPress user with the Editor role. A lower role can't read other people's drafts, because WordPress requires the "edit others' posts" capability for that. On that user's profile screen, under Application Passwords, add one named "Next.js preview" and copy it into WORDPRESS_APP_PASSWORD. Application passwords only work on sites served over HTTPS (or a local development site). This password can also edit content, so keep it on the server, and revoke it from the same screen if it ever leaks.

Add a draft fetcher to lib/wordpress.ts. It sends the login and has no "use cache", so drafts are never cached:

/** Any post by ID, drafts included, for previews. Never cached. */
export async function getDraft(id: string): Promise<Post | null> {
  const login = `${process.env.WORDPRESS_USER}:${process.env.WORDPRESS_APP_PASSWORD}`;
  const res = await fetch(`${API}/posts/${id}?${EMBED}&_fields=${POST_FIELDS}`, {
    headers: { Authorization: `Basic ${Buffer.from(login).toString("base64")}` },
  });
  return res.ok ? res.json() : null;
}
Enter fullscreen mode Exit fullscreen mode

Send previews to Next.js. Every Preview button in WordPress opens the post on the WordPress site with preview=true in the address. You might expect the preview_post_link filter to be enough, but for drafts the block editor builds that address itself and never runs the filter. Catching the preview request covers every editor, so add this to the must-use plugin:

/**
 * 2. Send previews to Next.js. The editor is logged in here, so check
 *    they can edit the post, then sign a link that works for that one
 *    post for an hour. Priority 9 runs this before the redirect below.
 */
add_action( 'template_redirect', function () {
    if ( ! is_preview() || ! is_singular( 'post' ) ) {
        return;
    }
    $id = get_queried_object_id();
    if ( ! current_user_can( 'edit_post', $id ) ) {
        return;
    }
    $expires = time() + HOUR_IN_SECONDS;
    wp_redirect( add_query_arg( array(
        'id'      => $id,
        'expires' => $expires,
        'sig'     => hash_hmac( 'sha256', $id . ':' . $expires, HEADLESS_PREVIEW_SECRET ),
    ), HEADLESS_FRONTEND . '/preview' ) );
    exit;
}, 9 );
Enter fullscreen mode Exit fullscreen mode

Why sign the link: Next.js can't see who is logged in to WordPress, so WordPress vouches for the visitor. It only signs a link after checking that the user can edit that post, and the signature ties the link to that one post for one hour. If someone shares the link, it can't be edited to open a different draft. To preview pages or custom post types, change two things: the is_singular( 'post' ) check in the plugin, and the endpoint in getDraft.

Build the preview page, which checks the signature before it fetches anything:

// app/preview/page.tsx
import { createHmac, timingSafeEqual } from "node:crypto";
import type { Metadata } from "next";
import { io } from "next/cache";
import { notFound } from "next/navigation";
import { Suspense } from "react";
import { Article } from "@/components/article";
import { getDraft } from "@/lib/wordpress";

export const metadata: Metadata = { robots: { index: false } };

export default function PreviewPage({ searchParams }: PageProps<"/preview">) {
  return (
    <Suspense fallback={<p>Loading preview…</p>}>
      <Preview searchParams={searchParams} />
    </Suspense>
  );
}

async function Preview({ searchParams }: Pick<PageProps<"/preview">, "searchParams">) {
  const { id, expires, sig } = await searchParams;
  await io(); // isSigned reads the clock, which must happen per request.
  if (!isSigned(id, expires, sig)) notFound();

  const post = await getDraft(id);
  if (!post) notFound();

  return (
    <main>
      <p role="status">Preview: this page isn&apos;t published yet.</p>
      <Article post={post} />
    </main>
  );
}

// Checks the link WordPress signed: right post, not expired.
function isSigned(id: unknown, expires: unknown, sig: unknown): id is string {
  const secret = process.env.PREVIEW_SECRET;
  if (!secret || typeof id !== "string" || typeof expires !== "string" || typeof sig !== "string") {
    return false;
  }
  if (!(Number(expires) * 1000 > Date.now())) return false; // Expired, or not a number.

  const expected = Buffer.from(createHmac("sha256", secret).update(`${id}:${expires}`).digest("hex"));
  const given = Buffer.from(sig);
  return given.length === expected.length && timingSafeEqual(given, expected);
}
Enter fullscreen mode Exit fullscreen mode

The query string is request data, so with Cache Components it has to be read inside <Suspense>. await io() (Next.js 16.3 and later) is needed because isSigned reads the clock. With Partial Prefetching, request data can resolve during a background prerender, and reading the time at that point is an error: without io(), the server logged exactly that in my tests.

The page is rendered for each request and sent with Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate, so neither the server nor a CDN keeps a copy. It also carries a noindex tag. The check refuses to run if PREVIEW_SECRET is missing, because an empty key would let anyone sign their own links, and it compares byte lengths before calling timingSafeEqual, which throws if they differ. In my tests, links signed by the PHP code were accepted, while edited, expired and unsigned links got the not-found page.

One limit to know about. When you preview a post that isn't a draft, such as a published or scheduled one, WordPress saves your unsaved changes as an autosave instead of into the post itself. The classic editor does the same for other people's drafts. This page shows the post as last saved, so if your editors need to see those changes, the REST API lists them at /wp/v2/posts/ID/autosaves.

Step 7: Keep search engines on the Next.js site

The WordPress theme still answers on cms.example.com, so every post exists twice. Add the last part of the must-use plugin:

/**
 * 3. Send anyone who opens the WordPress theme to the real site,
 *    so search engines only find one copy of each page.
 */
add_action( 'template_redirect', function () {
    if ( is_robots() || is_feed() || is_favicon() ) {
        return;
    }
    $path = is_singular( 'post' ) ? '/blog/' . get_queried_object()->post_name : '/';
    wp_redirect( HEADLESS_FRONTEND . $path, 301 );
    exit;
} );
Enter fullscreen mode Exit fullscreen mode

template_redirect runs when WordPress serves its front end: theme templates, plus feeds, robots.txt and the favicon, which this code leaves alone so feed readers keep working. The admin screens never run it, and REST API requests finish before it, so editors and Next.js aren't affected. Posts redirect to their new address and everything else goes to the home page. If your old URLs carried rankings, map them carefully, as covered in how to migrate a WordPress site without losing rankings.

Then give search engines a list of every post with app/sitemap.ts:

import type { MetadataRoute } from "next";
import { getAllPosts } from "@/lib/wordpress";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getAllPosts();

  return posts.map((post) => ({
    url: `https://www.example.com/blog/${post.slug}`,
    lastModified: new Date(`${post.modified_gmt}Z`),
  }));
}
Enter fullscreen mode Exit fullscreen mode

It shares the wordpress tag, so a new post appears in the sitemap as soon as the site refreshes. When I tested it against WordPress.org News, it listed all 1,126 posts, the same number the API reports. Submit it in Google Search Console once the site is live.

Before you launch

  • Permalinks are not set to Plain, and /wp-json/wp/v2/posts answers.
  • At least one post is published before the first build.
  • The secrets in wp-config.php and .env.local match, and none of them starts with NEXT_PUBLIC_.
  • Edit a published post, then load its page twice: the second load shows the change.
  • Click Preview on a draft and check that it opens on the Next.js site.
  • Run curl -I on a made-up slug and check for a 404.
  • Open an old WordPress post URL and check for a 301 to the new site.
  • If you run Next.js yourself behind a CDN, remember that the CDN can keep serving a page for a day, and for up to six more days as a stale copy while it refreshes, because Next.js sends s-maxage=86400, stale-while-revalidate=518400 with this cache setting. Purge the CDN on publish too.

Bottom line

Headless WordPress comes down to a short list of parts: a data file, two pages, a revalidation route, a preview page and one must-use plugin. Get publishing, previews and redirects working on day one, and editors keep the WordPress they know while visitors get static pages. If you're still deciding whether headless fits your project, start with when it's worth it.

Top comments (0)