Sheraz AhmadSenior Web Developer
Let's talk

Headless WordPress SEO in Next.js: Complete Setup Guide

Preserve your search visibility when decoupling. Here is how to map Yoast or Rank Math metadata, canonicals, sitemaps, and redirects into Next.js.

Getting headless WordPress SEO in Next.js right is the difference between a high-performing decoupled build and an immediate collapse in organic rankings. Decoupling WordPress strips away wp_head(), leaving your front end without automated meta tags, Open Graph data, canonical URLs, or Schema markup unless you explicitly wire them into the Next.js App Router.

This guide explains how to expose your existing Yoast SEO or Rank Math data via the REST API or WPGraphQL and accurately map it to Next.js metadata, route handlers, and middleware.

Quick answer

  • Expose native SEO plugin fields via REST API or the WPGraphQL SEO extensions (wp-graphql-yoast-seo or wp-graphql-rank-math).
  • Implement dynamic tags in Next.js using generateMetadata() in app/[...slug]/page.tsx, mapping titles, descriptions, and robots directly.
  • Clean WordPress backend domains out of canonicals, Open Graph URLs, and JSON-LD schema using a centralized URL replacement utility.
  • Generate your sitemap.xml using a Next.js Route Handler (app/sitemap.xml/route.ts) that fetches all published posts, pages, and custom post types.
  • Intercept legacy redirects in Next.js middleware.ts by checking your WordPress redirect table before returning a 404.

Expose Yoast or Rank Math over the WordPress API

To consume SEO data in Next.js, your headless backend must expose it cleanly without requiring you to manually parse arbitrary post meta. Both Yoast and Rank Math offer REST and GraphQL solutions.

Option 1: Native REST API (Zero Extra Plugins)

Yoast SEO automatically exposes a yoast_head_json object on core post and page endpoints. If you use Rank Math, add this snippet to a custom plugin to expose its complete metadata over the REST API:

add_action('rest_api_init', function () {
    register_rest_field(['post', 'page'], 'rank_math_seo', [
        'get_callback' => function ($post_arr) {
            $post_id = $post_arr['id'];
            
            return [
                'title'       => get_post_meta($post_id, 'rank_math_title', true) ?: get_the_title($post_id),
                'description' => get_post_meta($post_id, 'rank_math_description', true),
                'canonical'   => get_post_meta($post_id, 'rank_math_canonical_url', true) ?: get_permalink($post_id),
                'robots'      => get_post_meta($post_id, 'rank_math_robots', true) ?: ['index'],
                'og_image'    => get_post_meta($post_id, 'rank_math_facebook_image', true),
            ];
        },
        'schema' => null,
    ]);
});

Option 2: WPGraphQL with SEO Extensions

If your architecture uses WPGraphQL, install wp-graphql-yoast-seo or wp-graphql-rank-math. This attaches an seo node directly to your query types:

query GetPageSeo($uri: String!) {
  nodeByUri(uri: $uri) {
    ... on Page {
      title
      seo {
        title
        metaDesc
        canonical
        metaRobotsNoindex
        metaRobotsNofollow
        opengraphImage {
          sourceUrl
        }
        schema {
          raw
        }
      }
    }
  }
}

Map WordPress SEO data to Next.js metadata

The Next.js App Router uses the generateMetadata function to define <head> tags. When mapping data from headless WordPress, write a helper to swap the WordPress CMS URL with the Next.js production frontend URL.

// lib/seo.ts
const WP_URL = process.env.NEXT_PUBLIC_WORDPRESS_URL || 'https://cms.example.com';
const FRONTEND_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://example.com';

export function replaceBackendUrl(content: string): string {
  if (!content) return '';
  return content.replaceAll(WP_URL, FRONTEND_URL);
}

Now, implement generateMetadata in your dynamic catch-all route app/[...slug]/page.tsx:

import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { replaceBackendUrl } from '@/lib/seo';

interface Props {
  params: Promise<{ slug?: string[] }>;
}

async function getPageData(slugPath: string) {
  const res = await fetch(
    `${process.env.NEXT_PUBLIC_WORDPRESS_URL}/wp-json/wp/v2/pages?slug=${slugPath}&_embed`,
    { next: { revalidate: 3600 } }
  );
  const pages = await res.json();
  return pages?.[0] || null;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const resolvedParams = await params;
  const slug = resolvedParams.slug ? resolvedParams.slug.join('/') : 'home';
  const page = await getPageData(slug);

  if (!page) return {};

  // Using Yoast REST response example
  const yoast = page.yoast_head_json;
  const canonicalUrl = replaceBackendUrl(yoast?.canonical || `${process.env.NEXT_PUBLIC_SITE_URL}/${slug}`);

  return {
    title: yoast?.title || page.title.rendered,
    description: yoast?.description || '',
    alternates: {
      canonical: canonicalUrl,
    },
    robots: {
      index: yoast?.robots?.index !== 'noindex',
      follow: yoast?.robots?.follow !== 'nofollow',
    },
    openGraph: {
      title: yoast?.og_title || yoast?.title,
      description: yoast?.og_description || yoast?.description,
      url: canonicalUrl,
      images: yoast?.og_image ? [{ url: yoast.og_image[0].url }] : [],
      type: 'article',
    },
  };
}

export default async function Page({ params }: Props) {
  const resolvedParams = await params;
  const slug = resolvedParams.slug ? resolvedParams.slug.join('/') : 'home';
  const page = await getPageData(slug);

  if (!page) notFound();

  return (
    <main>
      <h1>{page.title.rendered}</h1>
      <div dangerouslySetInnerHTML={{ __html: replaceBackendUrl(page.content.rendered) }} />
    </main>
  );
}

Sanitizing canonicals, internal links, and JSON-LD schema

A common issue with decoupled WordPress setups is "domain leakage." If WordPress controls the schema, your Schema graph will emit https://cms.example.com as the canonical entity, confusing Google's indexer.

Never output raw JSON-LD or canonical tags from WordPress directly to your markup. Every backend URL must be string-replaced with the public Next.js domain before rendering, or Google will index your CMS subdomain.

Injecting cleaned JSON-LD into Next.js

Yoast outputs complete JSON-LD via yoast_head_json.schema. Here is how to sanitize and inject it safely:

// components/StructuredData.tsx
import { replaceBackendUrl } from '@/lib/seo';

interface SchemaProps {
  schemaData: Record<string, unknown>;
}

export function StructuredData({ schemaData }: SchemaProps) {
  if (!schemaData) return null;

  const sanitizedString = replaceBackendUrl(JSON.stringify(schemaData));
  
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: sanitizedString }}
    />
  );
}

Include this component in your layout or page file. Because replaceBackendUrl processes the entire stringified schema tree, nested references across WebSite, BreadcrumbList, and Article entities are systematically rewritten to point to your Next.js frontend origin.

Building dynamic XML sitemaps in Next.js

Do not point Google Search Console to your backend WordPress sitemaps (/wp-sitemap.xml or /sitemap_index.xml). Those files list the WordPress origin instead of the front end. Instead, generate a native XML sitemap in Next.js that fetches routes across your published content.

Create a Route Handler at app/sitemap.xml/route.ts:

import { NextResponse } from 'next/server';

const CMS_URL = process.env.NEXT_PUBLIC_WORDPRESS_URL;
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL;

export async function GET() {
  // Fetch IDs, slugs, and modified dates from WP REST API
  const [postsRes, pagesRes] = await Promise.all([
    fetch(`${CMS_URL}/wp-json/wp/v2/posts?per_page=100&_fields=slug,modified`),
    fetch(`${CMS_URL}/wp-json/wp/v2/pages?per_page=100&_fields=slug,modified`),
  ]);

  const posts = await postsRes.json();
  const pages = await pagesRes.json();

  const urls = [
    ...pages.map((page: { slug: string; modified: string }) => `
      <url>
        <loc>${SITE_URL}/${page.slug === 'home' ? '' : page.slug}</loc>
        <lastmod>${new Date(page.modified).toISOString()}</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
      </url>`),
    ...posts.map((post: { slug: string; modified: string }) => `
      <url>
        <loc>${SITE_URL}/blog/${post.slug}</loc>
        <lastmod>${new Date(post.modified).toISOString()}</lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
      </url>`),
  ];

  const sitemapXml = `<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
      ${urls.join('')}
    </urlset>`;

  return new NextResponse(sitemapXml, {
    headers: {
      'Content-Type': 'application/xml',
      'Cache-Control': 'public, s-maxage=86400, stale-while-revalidate=43200',
    },
  });
}

For sites containing thousands of URLs, avoid querying single collections with unpaginated requests. Split your sitemap into multiple indexes (sitemap-posts.xml, sitemap-pages.xml) using Next.js route segments.

Managing redirects without losing link equity

When content editors change a slug in WordPress, the backend creates a redirect record (using native WordPress wp_old_slug_redirect or plugins like Redirection). Next.js needs to catch these patterns before returning a 404.

Step 1: Register a REST API endpoint for redirects

If you use the Redirection plugin, add this endpoint inside WordPress to let Next.js query path matches:

add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/redirect', [
        'methods'             => 'GET',
        'permission_callback' => '__return_true',
        'callback'            => function ($request) {
            $path = sanitize_text_field($request->get_param('path'));
            if (empty($path)) {
                return new WP_Error('missing_path', 'Path required', ['status' => 400]);
            }

            if (function_exists('redirection_get_redirects')) {
                // If Redirection plugin is active
                $redirects = Redirection_Item::get_all_for_url($path);
                if (!empty($redirects)) {
                    return ['target' => $redirects[0]->get_action_data(), 'status' => 301];
                }
            }
            
            return ['target' => null];
        },
    ]);
});

Step 2: Query redirects inside Next.js middleware

Intercept dynamic routes inside middleware.ts before they hit missing page boundaries:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname;

  // Skip static assets and internal API routes
  if (
    pathname.startsWith('/_next') ||
    pathname.startsWith('/api') ||
    pathname.includes('.')
  ) {
    return NextResponse.next();
  }

  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_WORDPRESS_URL}/wp-json/custom/v1/redirect?path=${encodeURI(pathname)}`,
      { next: { revalidate: 300 } }
    );

    if (res.ok) {
      const data = await res.json();
      if (data?.target) {
        return NextResponse.redirect(new URL(data.target, request.url), data.status || 301);
      }
    }
  } catch (err) {
    // If redirect check fails, fall through to App Router
    console.error('Redirect lookup failed:', err);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

Checklist

  • The WordPress backend is blocked from public search engines via X-Robots-Tag: noindex, nofollow in server configurations or WordPress settings.
  • Yoast or Rank Math is actively configured on WordPress, with data exposed through REST API fields or WPGraphQL schema extensions.
  • generateMetadata correctly defines title, description, robots, alternates.canonical, and openGraph for all dynamic routes.
  • All references to the CMS domain in HTML content, canonical tags, and JSON-LD schema are stripped and replaced with the frontend domain.
  • Dynamic sitemap.xml route handler renders valid XML, correctly uses <lastmod> timestamps, and matches only production URLs.
  • A redirect lookup mechanism bridges WordPress redirect plugins with Next.js middleware.ts using proper 301 HTTP status codes.
  • Core Web Vitals (INP, LCP, CLS) are verified on production Next.js builds using Google Search Console URL Inspection.

Frequently asked questions

Should I index the headless WordPress backend domain?

No. You must configure your WordPress backend host to return noindex headers or block it via robots.txt. If search engines index your WordPress origin alongside your Next.js frontend, both domains will compete for rankings, resulting in duplicate content penalties and split page authority.

Do I need Yoast or Rank Math plugins for headless WordPress SEO?

While you can generate metadata manually using custom ACF fields, keeping Yoast or Rank Math is recommended. Content teams rely on their familiar admin interfaces, readability tools, snippet previews, and social graph inputs. You can simply expose and consume their structured output via APIs.

How do I handle canonical URLs in headless WordPress?

Retrieve the canonical URL string generated by your WordPress SEO plugin, then run it through a global string replacement function that replaces the WordPress CMS backend domain with your Next.js frontend domain before passing it to the App Router alternates metadata.

Reference documentation

Drafted with AI assistance. Code targets current WordPress, WooCommerce and Next.js APIs; test changes on a staging site before production.

Need a fast, modern website?

I'm Sheraz Ahmad, a senior WordPress and headless Next.js developer with 7+ years of shipping high-performance sites. Open to permanent roles, contracts and freelance projects.

Let's talk