Back to blog
November 26, 2026•25 views

Next.js and Headless WordPress: A Modern Setup for Fast, Dynamic Sites

Next.jsWordPressHeadless CMSWPGraphQLReactTutorial
Next.js and Headless WordPress: A Modern Setup for Fast, Dynamic Sites

Most WordPress sites I audit these days have the same problem. The content team loves the editor. The site itself loads like it is wading through mud because someone stacked 14 plugins on top of a theme that was already heavy years ago.

That is the exact spot where a Next.js headless WordPress setup earns its keep. Editors keep the WordPress admin they already know. Visitors get a React frontend that ships static HTML, hydrates fast, and does not care how many plugins live in the backend.

I have built this pattern for marketing sites, content-heavy blogs, and client portals. This Next.js headless WordPress tutorial walks through the setup I actually use: App Router, WPGraphQL, ISR, on-demand revalidation, image handling, and deployment. I will also show you where the REST API still makes sense, because it sometimes does.

Why go headless with WordPress at all?

The short answer: decoupling the content layer from the rendering layer buys you freedom on the frontend without retraining your editors.

Here is the honest comparison I give clients before we start.

Factor Traditional WordPress theme Headless WordPress + Next.js
Editor experience Native, familiar Native, familiar (unchanged)
Page speed Depends on theme + plugins Consistently fast, static-first
Hosting Shared PHP hosting works Needs Node hosting (Vercel, VPS, container)
Security surface Full WP exposed to public WP can sit behind auth or a private path
Frontend flexibility Constrained by PHP templating Any React component you want
Build complexity Low Medium to high
Cost at small scale Cheap Slightly higher (two runtimes)
Best fit Small brochure sites Content sites with real frontend demands

If your site is five pages and a contact form, a well-tuned WordPress theme is the sane choice. I will say that plainly. Headless adds moving parts, and you should only pay for them when the frontend actually needs the freedom.

Where it wins: content-heavy marketing sites, multi-channel content (web plus app plus email), design systems that must be consistent across products, and any site where Core Web Vitals are a business metric rather than a vanity number. If speed is the whole reason you are here, my guide to Next.js image optimization covers the frontend half of that equation in detail.

The architecture in one paragraph

WordPress stays as the content source. It exposes data through WPGraphQL (or the REST API). Next.js fetches that data at build or request time, renders it with the App Router, and caches the result with Incremental Static Regeneration. When an editor publishes, a webhook hits a Next.js route handler that revalidates the affected paths. The frontend never queries MySQL directly, and the WordPress install can live on a subdomain, behind basic auth, or on a private network.

Step 1: Prepare WordPress as a headless CMS

Start with a clean WordPress install. I usually spin one up locally with Docker so the whole stack is reproducible. (The command below assumes a separate MySQL container named db on the same Docker network, see the official WordPress Docker image docs for the full set of environment variables.)

docker run -d --name wp-headless -p 8080:80 \
  -e WORDPRESS_DB_HOST=db \
  -e WORDPRESS_DB_NAME=wp \
  wordpress:latest

Then, in the admin:

  1. Install WPGraphQL from the plugin directory (wpgraphql.com).
  2. Optionally install WPGraphQL for ACF if you use Advanced Custom Fields. It maps your field groups into the schema automatically.
  3. Install WPGraphQL CORS if your frontend and backend live on different origins during development.
  4. Create an application password under Users, Profile for any authenticated requests later (see the WordPress application passwords docs).

Once WPGraphQL is active, open /graphql in your browser. You should see the GraphiQL IDE. If you see a 404, your permalinks are probably set to "Plain". Switch them to "Post name" and try again. That one trips up more people than any other step.

Locking down the backend

A headless WordPress install should not be browsable as a normal site. Two options I use:

  • Basic auth at the reverse proxy (Nginx or Cloudflare Access), so only the Next.js server and editors can reach /graphql.
  • A private subdomain like cms.internal.example.com with IP allowlisting for the build server.

Do not skip this. A public /graphql endpoint with introspection enabled is an invitation to scrape your entire content database. For a broader hardening pass on the WordPress side, work through my WordPress security checklist before you point a public domain at the CMS.

Step 2: Scaffold the Next.js app

Create the project with the App Router. The examples below target Next.js 14 and 15; note that in Next.js 15 params in page components is a Promise and must be awaited, so adjust the signatures if you are on 15+ (see the Next.js App Router docs).

npx create-next-app@latest my-headless-site
# choose: TypeScript, App Router, Tailwind optional

Add environment variables for the WordPress endpoint.

# .env.local
WP_GRAPHQL_URL=https://cms.example.com/graphql
WP_REVALIDATE_SECRET=some-long-random-string
NEXT_PUBLIC_SITE_URL=https://www.example.com

A small fetch helper

I keep one typed fetch wrapper so I am not repeating headers everywhere.

// lib/wp.ts
const endpoint = process.env.WP_GRAPHQL_URL!;

export async function wpQuery<T>(
  query: string,
  variables: Record<string, unknown> = {},
  revalidate = 60
): Promise<T> {
  const res = await fetch(endpoint, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query, variables }),
    next: { revalidate },
  });

  if (!res.ok) {
    throw new Error(`WPGraphQL error: ${res.status} ${res.statusText}`);
  }

  const json = await res.json();
  if (json.errors) {
    throw new Error(json.errors.map((e: { message: string }) => e.message).join("; "));
  }
  return json.data as T;
}

The next: { revalidate } option is the important line. That is what wires this fetch into the Next.js cache and gives you ISR for free. (See the Next.js fetch caching and revalidation docs.)

Step 3: Fetch content in the App Router

Here is a post listing query. Note the first: 12 and the cursor fields, because pagination in GraphQL is cursor-based, not offset-based like REST.

// app/blog/page.tsx
import Link from "next/link";
import { wpQuery } from "@/lib/wp";

const POSTS_QUERY = /* GraphQL */ `
  query Posts($first: Int!) {
    posts(first: $first, where: { status: PUBLISH }) {
      nodes {
        id
        title
        slug
        excerpt
        date
      }
    }
  }
`;

type Post = { id: string; title: string; slug: string; excerpt: string; date: string };

export default async function BlogIndex() {
  const data = await wpQuery<{ posts: { nodes: Post[] } }>(POSTS_QUERY, { first: 12 }, 300);

  return (
    <main>
      <h1>Blog</h1>
      <ul>
        {data.posts.nodes.map((post) => (
          <li key={post.id}>
            <Link href={`/blog/${post.slug}`}>{post.title}</Link>
            <p dangerouslySetInnerHTML={{ __html: post.excerpt }} />
          </li>
        ))}
      </ul>
    </main>
  );
}

For the single post page, use generateStaticParams so each post is pre-rendered at build time.

// app/blog/[slug]/page.tsx
import { notFound } from "next/navigation";
import { wpQuery } from "@/lib/wp";

const SLUGS_QUERY = /* GraphQL */ `
  query Slugs { posts(first: 100, where: { status: PUBLISH }) { nodes { slug } } }
`;

const POST_QUERY = /* GraphQL */ `
  query Post($slug: ID!) {
    post(id: $slug, idType: SLUG) {
      title
      content
      date
      seo { title description }
    }
  }
`;

export async function generateStaticParams() {
  const data = await wpQuery<{ posts: { nodes: { slug: string }[] } }>(SLUGS_QUERY, {}, 3600);
  return data.posts.nodes.map((n) => ({ slug: n.slug }));
}

export default async function PostPage({ params }: { params: { slug: string } }) {
  const data = await wpQuery<{ post: { title: string; content: string } | null }>(
    POST_QUERY,
    { slug: params.slug },
    300
  );
  if (!data.post) notFound();

  return (
    <article>
      <h1>{data.post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: data.post.content }} />
    </article>
  );
}

The revalidate = 300 means each post page rebuilds in the background every five minutes, or immediately when a webhook fires. Visitors always get a cached response.

Step 4: On-demand revalidation with a webhook

Time-based revalidation is fine as a fallback. On-demand revalidation is what makes editors happy, because publish means publish, not "publish and wait up to five minutes".

Create a route handler in Next.js.

// app/api/revalidate/route.ts
import { revalidatePath } from "next/cache";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  const secret = req.nextUrl.searchParams.get("secret");
  if (secret !== process.env.WP_REVALIDATE_SECRET) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await req.json();
  const slug = body?.post?.post_name;

  if (slug) revalidatePath(`/blog/${slug}`);
  revalidatePath("/blog");
  revalidatePath("/");

  return NextResponse.json({ revalidated: true, slug });
}

Then install a plugin like WP Webhooks or write a tiny mu-plugin that fires a POST to https://www.example.com/api/revalidate?secret=... on save_post. I prefer the mu-plugin because it is one file and no UI.

<?php
// wp-content/mu-plugins/revalidate.php
add_action('save_post', function ($post_id, $post) {
    if (wp_is_post_revision($post_id) || $post->post_status !== 'publish') return;

    wp_remote_post('https://www.example.com/api/revalidate?secret=' . WP_REVALIDATE_SECRET, [
        'body' => wp_json_encode(['post' => ['post_name' => $post->post_name]]),
        'headers' => ['Content-Type' => 'application/json'],
        'timeout' => 5,
    ]);
}, 10, 2);

Keep the secret in wp-config.php as a constant, not hardcoded in the file.

Step 5: Images, SEO, and the boring stuff that matters

WordPress media in next/image

WPGraphQL returns a sourceUrl pointing at your WordPress host. Configure remotePatterns in next.config.js so Next.js will optimize those images. (See the next/image remote patterns docs.)

// next.config.js
module.exports = {
  images: {
    remotePatterns: [
      { protocol: "https", hostname: "cms.example.com", pathname: "/wp-content/uploads/**" },
    ],
  },
};

Then render with <Image src={sourceUrl} width={featuredImage.node.mediaDetails.width} height={...} alt={altText} />. If you skip this and use a plain <img>, you will lose the whole point of the frontend being fast. The Next.js image optimization guide goes deeper on formats, sizes, and priority hints.

Metadata mapping

Use the generateMetadata export and pull from your SEO plugin's GraphQL fields (Yoast and RankMath both have WPGraphQL extensions). If you are not using one, map title and excerpt manually and keep it simple.

export async function generateMetadata({ params }: { params: { slug: string } }) {
  const data = await wpQuery<{ post: { title: string; seo: { title: string; description: string } } }>(
    POST_QUERY, { slug: params.slug }, 300
  );
  return {
    title: data.post.seo?.title ?? data.post.title,
    description: data.post.seo?.description ?? "",
    alternates: { canonical: `/blog/${params.slug}` },
  };
}

WPGraphQL vs REST API: which should you use?

Both work. I default to GraphQL, but I have shipped REST-based headless sites too, and there are cases where it is the better call.

Consideration WPGraphQL WP REST API
Setup Needs a plugin Built in
Query precision Ask for exactly the fields you need Fixed payloads, often oversized
Nested data (post + author + media + terms) One request Multiple requests or _embed
Learning curve GraphQL schema, queries Plain HTTP, easier for beginners
Caching POST requests, needs care at CDN GET requests, cache-friendly
Auth Application passwords / JWT plugin Cookie or application passwords
Plugin support Requires extensions for ACF, SEO Works with core fields out of the box

My rule: if your content model is rich (custom post types, ACF fields, taxonomies), use WPGraphQL. If you are pulling a handful of posts into a marketing page and want zero extra plugins, REST is fine.

Deployment notes

  • Vercel is the path of least resistance. Set WP_GRAPHQL_URL and WP_REVALIDATE_SECRET in project settings, and point the webhook at the production domain.
  • Self-hosted (Docker/Kubernetes) gives you control over caching and lets you keep WordPress on the same private network. I run this setup on AWS for clients with strict data rules.
  • Latency matters. If your WordPress backend is on a shared host in one region and your Next.js builds happen in another, build times suffer. In my experience working with clients across Bangladesh, the USA, and Australia, putting the CMS and the build runner in the same region (or at least the same continent) cuts build time noticeably. It is a small infra decision with a large payoff.

Common pitfalls I have hit

  • Permalinks set to Plain break WPGraphQL. Always switch to Post name.
  • Public /graphql with introspection on. Lock it down.
  • No remotePatterns for the WP media host, so next/image throws at runtime.
  • Forgetting revalidatePath on the index page, so the post updates but the listing does not.
  • Draft preview missing. Add Next.js draft mode plus a WPGraphQL auth token if editors need to preview before publishing. It is worth the extra hour.
  • Assuming ISR is instant. It is stale-while-revalidate. The first visitor after a change may see the old page for a moment.

FAQ

Do I need WPGraphQL, or can I use the REST API with Next.js?

You can use either. The REST API is built in and fine for simple sites. WPGraphQL is worth the plugin when you have custom post types, ACF fields, or want nested data in a single request. I default to GraphQL for content-heavy builds and REST for quick marketing pages.

How does Incremental Static Regeneration work with WordPress?

Next.js caches the rendered page and serves it statically. With revalidate set on the fetch, it refreshes in the background after the interval. With a webhook from WordPress to a Next.js route handler calling revalidatePath, it refreshes immediately on publish. You usually want both.

Can editors still preview drafts in a headless setup?

Yes. Enable Next.js draft mode, add an authenticated GraphQL request using an application password, and route preview links from WordPress to your frontend. It takes a bit of setup but keeps the editorial workflow intact.

Is headless WordPress slower to build than a normal theme?

The first build is slower because every page is pre-rendered. After that, ISR and on-demand revalidation keep things fast. The real cost is the extra infrastructure (Node hosting plus the WordPress backend) and the need to maintain a webhook and a schema. For small sites, that overhead is not worth it.

Wrapping up

Headless WordPress with Next.js is not magic, and it is not for every site. But when the frontend needs to be fast, flexible, and consistent across products, this setup delivers. WordPress stays the editor's home, Next.js handles rendering, and ISR plus a webhook keeps everything fresh without rebuilding the whole site on every publish.

If you are weighing this for a project, or you already have a WordPress install that has outgrown its theme and want to move it to a Next.js frontend without losing your editorial workflow, that is exactly the kind of migration I do. You can reach out through the contact page and tell me what you are working with. I will tell you honestly whether headless is the right call or whether a tuned theme will get you there for less. And if you are deciding who should build it, my guide to hiring a full-stack developer covers the Next.js, Node.js, and AI automation skills to screen for.

Frequently asked questions

Do I need WPGraphQL, or can I use the REST API with Next.js?

You can use either. The REST API is built in and fine for simple sites. WPGraphQL is worth the plugin when you have custom post types, ACF fields, or want nested data in a single request. I default to GraphQL for content-heavy builds and REST for quick marketing pages.

How does Incremental Static Regeneration work with WordPress?

Next.js caches the rendered page and serves it statically. With revalidate set on the fetch, it refreshes in the background after the interval. With a webhook from WordPress to a Next.js route handler calling revalidatePath, it refreshes immediately on publish. You usually want both.

Can editors still preview drafts in a headless setup?

Yes. Enable Next.js draft mode, add an authenticated GraphQL request using an application password, and route preview links from WordPress to your frontend. It takes a bit of setup but keeps the editorial workflow intact.

Is headless WordPress slower to build than a normal theme?

The first build is slower because every page is pre-rendered. After that, ISR and on-demand revalidation keep things fast. The real cost is the extra infrastructure (Node hosting plus the WordPress backend) and the need to maintain a webhook and a schema. For small sites, that overhead is not worth it.

Share this post

Native Web Share is available on mobile, so that share sheet includes Instagram and any other app you have installed.

Let's Connect

Get In Touch

Let's build something premium together.

Contact info

Follow me
Chat on WhatsApp