Artı Teknoloji - Teknolojiye Artı
Headless WordPress Architecture: WPGraphQL, Next.js App Router & Edge ISR - Baskı Önizleme

+- Artı Teknoloji - Teknolojiye Artı (https://www.artiteknoloji.com)
+-- Forum: Web Tabanlı Uygulamalar (https://www.artiteknoloji.com/forumdisplay.php?fid=44)
+--- Forum: WordPress (https://www.artiteknoloji.com/forumdisplay.php?fid=47)
+--- Konu Başlığı: Headless WordPress Architecture: WPGraphQL, Next.js App Router & Edge ISR (/showthread.php?tid=576)



Headless WordPress Architecture: WPGraphQL, Next.js App Router & Edge ISR - Wertomy® - 19-11-2026

Headless WordPress Architecture: WPGraphQL, Next.js App Router & Edge ISR

For editorial teams, WordPress’s Gutenberg block editor, granular role capabilities, and mature publishing workflows remain unmatched. Yet on the public delivery tier, coupling high-traffic media portals or enterprise SaaS marketing sites directly to a monolithic PHP theme introduces severe concurrency limits, plugin script bloat, and security exposure across every anonymous pageview. Decoupling WordPress into a pure headless content backend—exposing strongly typed schemas via WPGraphQL, rendering React Server Components on Next.js App Router, and invalidating global Edge Incremental Static Regeneration (ISR) caches within 300 milliseconds of clicking "Publish"—delivers instant sub-30ms global page loads while completely shielding wp-admin from public internet traffic.



Decoupling Editorial Workflows from Public Edge Delivery

In a traditional coupled WordPress deployment, every uncached visitor request boots WordPress core, loads 30+ active plugins, executes database queries, and renders HTML through PHP templates. Moving to a headless topology splits responsibilities across two isolated tiers:

[table]
[tr]
[td]Architectural Concern[/td]
[td]Coupled Monolithic WordPress[/td]
[td]Headless WordPress + Next.js Edge[/td]
[/tr]
[tr]
[td]Public Attack Surface[/td]
[td]Origin PHP/MySQL exposed directly to global traffic & bots[/td]
[td]Origin locked behind Cloudflare Zero Trust / IP allowlist; edge serves static HTML[/td]
[/tr]
[tr]
[td]Data Transport Layer[/td]
[td]Server-side WP_Query loops inside theme PHP templates[/td]
[td]Single-round-trip WPGraphQL queries fetching exact required fields[/td]
[tr]
[td]Cache Invalidation[/td]
[td]Full-page purge plugins clearing entire Varnish/Nginx caches[/td]
[td]Surgical tag-based revalidateTag() purging only modified articles[/td]
[/tr]
[tr]
[td]Front-End Bundle & Hydration[/td]
[td]Dozens of conflicting plugin jQuery/CSS assets on every page[/td]
[td]Zero-bundle React Server Components + selective client hydration[/td]
[/tr]
[tr]
[td]Multi-Channel Syndication[/td]
[td]Requires separate RSS/REST adapters for mobile or docs apps[/td]
[td]Unified GraphQL content graph powering web, iOS/Android, and newsletters[/td]
[/tr]
[/table]

Engineering Strongly Typed Content Graphs with WPGraphQL

While WordPress includes a built-in REST API (/wp-json/wp/v2/posts), REST endpoints over-fetch massive JSON payloads packed with unused revision links, unparsed HTML blobs, and separate round-trips for featured media, author profiles, and custom ACF fields. WPGraphQL solves this under-fetching/over-fetching dilemma by exposing an introspective, strongly typed graph where Next.js requests the exact fields needed for a given route in one HTTP POST/GET call:

Kod:
query GetArticleBySlug($slug: ID!) {
  post(id: $slug, idType: SLUG) {
    databaseId
    title
    slug
    dateGmt
    modifiedGmt
    excerpt
    content(format: RENDERED)
    author {
      node {
        name
        slug
        avatar {
          url
          width
          height
        }
      }
    }
    categories(first: 3) {
      nodes {
        name
        slug
      }
    }
    featuredImage {
      node {
        sourceUrl(size: LARGE)
        altText
        mediaDetails {
          width
          height
        }
      }
    }
    seo {
      title
      metaDesc
      canonical
      schema {
        raw
      }
    }
  }
}
To prevent malicious clients from crafting deeply nested circular GraphQL queries (such as querying posts -> author -> posts -> author ten levels deep to exhaust PHP memory), enable WPGraphQL Query Depth Limiting, disable public GraphQL introspection in production, and activate WPGraphQL Smart Cache backed by Redis object caching so repeated GraphQL queries resolve straight from RAM.

Alıntı:Never let public browsers query your WordPress GraphQL origin directly in production; execute all GraphQL fetches server-side inside Next.js React Server Components and cache responses at the edge using surgical cache tags.

Next.js App Router Data Fetching and Tag-Based Cache Architecture

Inside Next.js App Router, wrapping your WPGraphQL client around native fetch() cache tags (next: { tags: [...] }) turns static edge pages into dynamically invalidatable views without sacrificing CDN speed:

Kod:
// lib/wordpress.ts — Server-Only WPGraphQL Fetcher with Surgical Cache Tags
export async function fetchWordPressGraphQL<T>(
  query: string,
  variables: Record<string, unknown> = {},
  tags: string[] = ['wordpress']
): Promise<T> {
  const endpoint = process.env.WP_GRAPHQL_ENDPOINT!;

  const response = await fetch(endpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Headless-Secret': process.env.WP_HEADLESS_ORIGIN_TOKEN!,
    },
    body: JSON.stringify({ query, variables }),
    next: {
      revalidate: 3600, // Fallback 1-hour background ISR window
      tags,             // Granular tags e.g. ['post:1042', 'category:engineering']
    },
  });

  if (!response.ok) {
    throw new Error(`WPGraphQL origin returned HTTP ${response.status}`);
  }

  const json = await response.json();
  if (json.errors) {
    throw new Error(`GraphQL execution error: ${JSON.stringify(json.errors)}`);
  }

  return json.data as T;
}
Notice the X-Headless-Secret header included on every server-side fetch: configuring Nginx or Cloudflare WAF on your WordPress origin to drop any /graphql request lacking that shared secret ensures external scrapers cannot hammer your origin database directly.

Instant On-Demand Edge Revalidation When Editors Click "Publish"

The classic complaint against static headless architectures is stale content—editors update a breaking news headline in WordPress and wait ten minutes for CDN caches to expire. Wiring a lightweight WordPress save_post webhook directly into a Next.js Route Handler eliminates cache staleness permanently:

Kod:
<?php
// mu-plugins/headless-isr-webhook.php — Trigger Instant Next.js Cache Purge on Publish
add_action('transition_post_status', function (string $newStatus, string $oldStatus, WP_Post $post): void {
    if (wp_is_post_revision($post->ID) || wp_is_post_autosave($post->ID)) {
        return;
    }

    if ($newStatus !== 'publish' && $oldStatus !== 'publish') {
        return;
    }

    $tags = [
        'post:' . $post->ID,
        'slug:' . $post->post_name,
        'archive:latest',
    ];

    wp_remote_post('https://www.example.com/api/revalidate', [
        'timeout'  => 2,
        'blocking' => false, // Non-blocking so Gutenberg Save button feels instantaneous
        'headers'  => [
            'Content-Type' => 'application/json',
            'X-Webhook-Signature' => hash_hmac('sha256', wp_json_encode($tags), HEADLESS_REVALIDATE_SECRET),
        ],
        'body' => wp_json_encode(['tags' => $tags]),
    ]);
}, 10, 3);
Inside Next.js (app/api/revalidate/route.ts), your Route Handler verifies the HMAC-SHA256 signature and calls revalidateTag(tag) for each affected tag—purging that exact article and the homepage feed across global edge PoPs in under 300 milliseconds while leaving thousands of unrelated cached pages untouched.

Solving Headless Gotchas: Live Previews, Sitemaps, and Redirects

Before decommissioning your legacy PHP theme, close three operational gaps that frequently trip up first-time headless deployments:

  1. Authenticated Draft Previews via Next.js Draft Mode: Override WordPress’s default preview link filter (preview_post_link) to point editors to https://www.example.com/api/preview?id=1042&token=..., which verifies a short-lived signed JWT, enables Next.js draftMode().enable(), and queries unpublished revisions using an authenticated WPGraphQL application password.
  2. Redirecting Legacy WordPress Theme Routes to wp-admin: Install a minimal headless placeholder theme on WordPress whose index.php immediately issues a 301 redirect to your public Next.js frontend domain so search crawlers never index unstyled origin URLs.
  3. Unified XML Sitemaps & SEO Metadata: Either proxy Yoast SEO / Rank Math XML sitemaps cleanly through Next.js rewrites (rewriting origin hostnames to your public domain) or generate dynamic app/sitemap.ts feeds directly from lightweight WPGraphQL slug queries.

By uniting WordPress’s best-in-class editorial experience with WPGraphQL’s typed data graph, React Server Components, and HMAC-authenticated On-Demand ISR revalidation, engineering teams achieve uncompromising Core Web Vitals, ironclad origin security, and instant publishing agility.