Author: ratrijawanes

  • Headless WordPress + Next.js: What Nobody Warns You About

    Headless WordPress sounds clean on paper: WordPress handles content, Next.js handles the frontend, GraphQL connects them. Editors love the familiar dashboard. Developers get a modern React stack. Everyone wins.

    In practice, you will hit a wall — probably several. I built jawanes.com as a headless WordPress + Next.js site, and I’ve helped clients through similar setups at Jupitr Agency. Here are the actual problems you’ll encounter, and exactly how to fix them.

    Gotcha #1: GraphQL Caching Breaks Preview Mode

    WPGraphQL caches responses aggressively. That’s great for published content — but it completely breaks WordPress’s built-in preview functionality. When an editor clicks ‘Preview’ on a draft post, they see the cached published version, not their draft.

    ⚠ Problem: Draft previews show stale cached data instead of the actual draft content.

    The fix involves setting up a dedicated preview route in Next.js and passing a preview token from WordPress. In your Next.js app:

    // pages/api/preview.js
    
    export default async function handler(req, res) {
      const { secret, id, slug } = req.query
      if (secret !== process.env.WP_PREVIEW_SECRET) {
        return res.status(401).json({ message: "Invalid token" })
      }
      res.setPreviewData({ id, slug })
      res.redirect(`/posts/${slug}`)
    }

    In your post page, check for preview mode and bypass the cache:

    // pages/posts/[slug].js
    
    export async function getStaticProps({ params, preview = false, previewData }) {
      const post = await getPost(
        preview ? previewData.id : params.slug,
        { preview }  // Pass preview flag to your GraphQL query
      )
      return { props: { post, preview } }
    }

    ✓ Fix: Always implement preview mode before launch. Your editors will need it immediately, and retrofitting it is painful.

    Gotcha #2: ACF Fields Don’t Appear in WPGraphQL Automatically

    You installed ACF (Advanced Custom Fields), created your field groups, populated content — and then query WPGraphQL expecting the data. Nothing. The fields aren’t there.

    ⚠ Problem: ACF fields are invisible to WPGraphQL by default. Each field group must be explicitly registered.

    You have two options. Option A (quick): Use the WPGraphQL for ACF plugin, then enable GraphQL for each field group in the ACF UI under ‘GraphQL’ settings.

    Option B (no extra plugin): Register fields manually using PHP. This is more work but keeps your plugin count down:

    // functions.php
    
    add_action("graphql_register_types", function() {
      register_graphql_field("Post", "customBio", [
        "type" => "String",
        "description" => "Author bio from ACF",
        "resolve" => function($post) {
          return get_field("custom_bio", $post->databaseId);
        }
      ]);
    });

    ✓ Fix: For most projects, the WPGraphQL for ACF plugin is worth it. Manual registration is fine for a few fields but becomes a maintenance burden at scale.

    Gotcha #3: ISR Cache Doesn’t Invalidate on Content Updates

    Next.js Incremental Static Regeneration (ISR) is perfect for headless WordPress — pages regenerate in the background as editors publish. Except: by default, ISR only knows to regenerate when someone visits the page. If no one visits, the cache sits stale indefinitely.

    More critically: when an editor updates a post, Next.js has no idea. It only regenerates on its own schedule (whatever you set as revalidate).

    ⚠ Problem: Content updates in WordPress don’t trigger Next.js to regenerate the affected pages.

    The solution is on-demand revalidation. Set up a WordPress hook that pings your Next.js revalidation endpoint whenever a post is saved:

    // functions.php
    
    function trigger_nextjs_revalidation($post_id) {
    
      if (wp_is_post_revision($post_id)) return;
      $slug = get_post_field("post_name", $post_id);
      $secret = getenv("NEXTJS_REVALIDATION_SECRET");
      wp_remote_post("https://yoursite.com/api/revalidate", [
        "body" => json_encode(["slug" => $slug, "secret" => $secret]),
    
        "headers" => ["Content-Type" => "application/json"],
      ]);
    }
    
    add_action("save_post", "trigger_nextjs_revalidation");

    And the Next.js endpoint:

    // pages/api/revalidate.js
    
    export default async function handler(req, res) {
      if (req.body.secret !== process.env.NEXTJS_REVALIDATION_SECRET) {
        return res.status(401).json({ message: "Invalid secret" })
      }
    
      await res.revalidate(`/posts/${req.body.slug}`)
      return res.json({ revalidated: true })
    }

    ✓ Fix: Wire up on-demand revalidation before your first content editor touches the CMS. It’s 30 minutes of setup that saves hours of ‘why isn’t my content updating?’ conversations.

    Gotcha #4: The Gutenberg Block Rendering Problem

    WordPress stores Gutenberg block content as comment-annotated HTML (<!– wp:paragraph –>). WPGraphQL returns this raw string. If you dump it directly into your React component, you get unstyled HTML — possibly with broken layout if editors used complex blocks like columns or galleries.

    ⚠ Problem: Gutenberg block markup doesn’t translate directly into styled React components.

    You have three real options:

    • Use the rendered HTML field (contentRendered) and scope your CSS tightly. Quickest to ship, hardest to control styling.
    • Parse blocks with a library like @wordpress/blocks on the server and map each block type to a React component. Most flexible, most work.
    • Restrict editors to Classic Editor or a defined subset of Gutenberg blocks, and handle only those. Pragmatic for small teams.

    For jawanes.com, I went with option 3 — a whitelist of allowed blocks and CSS scoping. For client projects with more complex editorial needs, option 2 is worth the investment.

    Gotcha #5: GraphQL Query Depth and Performance

    WPGraphQL lets you request deeply nested data in a single query. That’s powerful — but it’s easy to write queries that either hit WPGraphQL’s depth limit or return enormous payloads that slow down page generation.

    ⚠Problem: Unbounded GraphQL queries cause slow builds and occasionally hit server memory limits.

    A few rules I follow:

    • Never query fields you don’t need. Be explicit — don’t rely on fragments that pull everything.
    • Set a max depth in WPGraphQL settings (I use 7 as a default).
    • For lists (post archives, category pages), fetch only the data you need for the card UI, not the full content.
    // Good: archive query — only what the card needs
    query GetPostList {
      posts(first: 10) {
        nodes {
          title
          slug
          excerpt
          featuredImage { node { sourceUrl altText } }
        }
      }
    }
    // Bad: fetching full content for a list page
    // query GetPostList { posts { nodes { content ... } } }

    Gotcha #6: CORS and Authentication in Production

    Local development works fine. You push to production and suddenly your GraphQL requests are blocked by CORS. Or your JWT authentication stops working. Or both.

    ⚠ Problem: CORS headers aren’t set for your frontend domain, and auth tokens may behave differently across environments.

    In your WordPress functions.php or a site-specific plugin:

    // Allow your Next.js frontend domain
    
    add_action("init", function() {
    
      $allowed = ["https://yoursite.com", "http://localhost:3000"];
    
      $origin = $_SERVER["HTTP_ORIGIN"] ?? "";
    
      if (in_array($origin, $allowed)) {
        header("Access-Control-Allow-Origin: $origin");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
      }
    
    });

    ✓ Fix: Allowlist both your production domain and localhost in the CORS config. Never use wildcard (*) in production — it allows any site to query your WordPress backend.

    The Quick Reference

    If you’re starting a headless WordPress + Next.js project, here’s what to set up before you write a single frontend component:

    • WPGraphQL + WPGraphQL for ACF installed and field groups registered
    • Preview mode endpoint wired up (/api/preview)
    • On-demand revalidation endpoint wired up (/api/revalidate)
    • CORS headers configured for your frontend domain(s)
    • GraphQL max depth set in WPGraphQL settings
    • Gutenberg block strategy decided (CSS scope, component map, or block whitelist)

    The headless WordPress pattern is solid — it just has more moving parts than a traditional WordPress setup. Once these pieces are in place, the developer experience is genuinely good.