Headless WordPress + Next.js: SEO-Optimized Decoupled Publishing

Build scalable headless WordPress sites with Next.js and TypeScript. Master ISR, Core Web Vitals, REST API integration, and production patterns.

0

Headless WordPress separates content management from presentation. Instead of serving HTML directly, WordPress becomes a REST API backend while Next.js handles rendering, routing, and performance optimization. This decoupling gives you content independence, global CDN delivery, and the ability to optimize for Core Web Vitals without the constraints of a monolithic architecture.

This guide walks through architecting a production-ready headless setup: connecting WordPress REST APIs to Next.js, using Incremental Static Regeneration for SEO-friendly updates, typing content with TypeScript, and deploying at scale.

Why Headless WordPress Plus Next.js

Traditional WordPress serves HTML directly from a single server. Your site’s performance depends on server resources, plugin load, and database queries. Headless flips this model: WordPress stores and serves JSON; Next.js pre-renders pages and caches them globally.

The practical wins:

  • Content teams update WordPress without triggering frontend builds or deployments
  • Next.js handles rendering, caching, and CDN distribution independently
  • You optimize Core Web Vitals through Next.js Image, dynamic imports, and ISR without plugin overhead
  • Multiple frontends (web, mobile, headless API) share the same content backend
  • Scaling content delivery doesn’t require scaling WordPress infrastructure

For publishing platforms, news sites, or enterprise content hubs, this separation is transformative. Your writers work in a familiar CMS. Your engineers ship optimized frontends. They evolve independently.

Connecting WordPress REST API to Next.js

WordPress exposes a REST API at /wp-json/wp/v2/. You can fetch posts, pages, custom post types, taxonomies, and media without touching PHP.

Start with a simple data-fetching layer. Create a lib file to handle WordPress requests:

// lib/wordpress.ts
const WP_API = process.env.NEXT_PUBLIC_WP_API_URL || 'https://your-site.com';

interface WPPost {
  id: number;
  title: { rendered: string };
  content: { rendered: string };
  excerpt: { rendered: string };
  slug: string;
  date: string;
  featured_media: number;
  _links?: { 'wp:featuredmedia'?: Array<{ href: string }> };
}

export async function getPost(slug: string): Promise<WPPost | null> {
  try {
    const res = await fetch(
      `${WP_API}/wp-json/wp/v2/posts?slug=${slug}&_embed`,
      { next: { revalidate: 3600 } }
    );
    if (!res.ok) return null;
    const posts: WPPost[] = await res.json();
    return posts[0] || null;
  } catch (error) {
    console.error('Failed to fetch post:', error);
    return null;
  }
}

export async function getAllPosts(
  page: number = 1,
  perPage: number = 10
): Promise<{ posts: WPPost[]; total: number }> {
  try {
    const res = await fetch(
      `${WP_API}/wp-json/wp/v2/posts?page=${page}&per_page=${perPage}&_embed`,
      { next: { revalidate: 1800 } }
    );
    if (!res.ok) throw new Error('Failed to fetch posts');
    const posts: WPPost[] = await res.json();
    const total = parseInt(res.headers.get('X-WP-Total') || '0', 10);
    return { posts, total };
  } catch (error) {
    console.error('Failed to fetch all posts:', error);
    return { posts: [], total: 0 };
  }
}

The key here is the next: { revalidate: ... } option. This tells Next.js to cache the fetch result and revalidate after a set interval (in seconds). It’s the foundation of ISR.

Create a simple post page using this data:

// app/blog/[slug]/page.tsx
import { getPost, getAllPosts } from '@/lib/wordpress';
import { notFound } from 'next/navigation';

export async function generateStaticParams() {
  const { posts } = await getAllPosts(1, 50);
  return posts.map((post) => ({ slug: post.slug }));
}

export async function generateMetadata({ params }: { params: { slug: string } }) {
  const post = await getPost(params.slug);
  if (!post) return {};
  return {
    title: post.title.rendered,
    description: post.excerpt.rendered.replace(/<[^>]*>/g, '').slice(0, 155),
  };
}

export default async function PostPage({ params }: { params: { slug: string } }) {
  const post = await getPost(params.slug);
  if (!post) notFound();

  return (
    <article>
      <h1>{post.title.rendered}</h1>
      <time>{new Date(post.date).toLocaleDateString()}</time>
      <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
    </article>
  );
}

generateStaticParams tells Next.js which slugs to pre-render at build time. Combined with revalidate, this creates ISR: pages are static by default, but they regenerate in the background when WordPress content changes.

Incremental Static Regeneration for SEO

ISR is the bridge between static performance and dynamic content. On-demand revalidation lets you rebuild specific pages when WordPress data changes, without a full site rebuild.

Set up a WordPress webhook to trigger revalidation. First, create a revalidation endpoint in Next.js:

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

const REVALIDATE_SECRET = process.env.REVALIDATE_SECRET;

export async function POST(request: NextRequest) {
  const secret = request.headers.get('x-revalidate-secret');

  if (secret !== REVALIDATE_SECRET) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const body = await request.json();
  const { post_id, post_name } = body;

  try {
    revalidatePath(`/blog/${post_name}`);
    revalidatePath('/blog');
    return NextResponse.json({ revalidated: true, now: Date.now() });
  } catch (error) {
    return NextResponse.json(
      { error: 'Revalidation failed' },
      { status: 500 }
    );
  }
}

In WordPress, install a plugin like WP Webhooks or create a simple action hook that sends a POST request to your Next.js API whenever a post is published or updated:

// In WordPress theme or plugin
add_action('publish_post', function($post_id) {
  $post = get_post($post_id);
  $url = 'https://your-nextjs-site.com/api/revalidate';
  
  wp_remote_post($url, array(
    'headers' => array(
      'x-revalidate-secret' => $_ENV['REVALIDATE_SECRET'],
      'Content-Type' => 'application/json',
    ),
    'body' => json_encode(array(
      'post_id' => $post_id,
      'post_name' => $post->post_name,
    )),
  ));
});

Now when a post is published in WordPress, Next.js immediately regenerates that page in the background. Users see the new content within seconds, and search engines see updated HTML on their next crawl.

TypeScript Type Safety for Content Schemas

WordPress REST API returns JSON, but the structure varies by post type, custom fields, and plugins. TypeScript helps catch mismatches early.

Define types for your content schema. If you’re using ACF (Advanced Custom Fields) or custom post types, model them explicitly:

// lib/types.ts
export interface WPAuthor {
  id: number;
  name: string;
  avatar_urls: { [key: string]: string };
}

export interface WPFeaturedImage {
  id: number;
  source_url: string;
  alt_text: string;
  title: { rendered: string };
}

export interface WPPost {
  id: number;
  title: { rendered: string };
  content: { rendered: string };
  excerpt: { rendered: string };
  slug: string;
  date: string;
  author: number;
  featured_media: number;
  categories: number[];
  tags: number[];
  _embedded?: {
    'author'?: WPAuthor[];
    'wp:featuredmedia'?: WPFeaturedImage[];
  };
}

export interface WPCategory {
  id: number;
  name: string;
  slug: string;
  description: string;
  count: number;
}

export interface WPTag {
  id: number;
  name: string;
  slug: string;
  description: string;
  count: number;
}

For custom fields, extend the types:

// lib/types.ts (continued)
export interface WPPostWithACF extends WPPost {
  acf?: {
    featured_quote?: string;
    reading_time?: number;
    related_posts?: number[];
    seo_title?: string;
    seo_description?: string;
  };
}

Update your data-fetching functions to use these types:

// lib/wordpress.ts (updated)
export async function getPost(slug: string): Promise<WPPostWithACF | null> {
  const res = await fetch(
    `${WP_API}/wp-json/wp/v2/posts?slug=${slug}&_embed`,
    { next: { revalidate: 3600 } }
  );
  if (!res.ok) return null;
  const posts: WPPostWithACF[] = await res.json();
  return posts[0] || null;
}

TypeScript now catches missing fields, wrong types, and API contract changes at build time, not at runtime in production.

Optimizing Core Web Vitals

Headless Next.js gives you fine-grained control over performance. Core Web Vitals measure Largest Contentful Paint (LCP), Cumulative Layout Shift (CLS), and Interaction to Next Paint (INP).

Optimize images first. WordPress stores images at various sizes. Use Next.js Image for automatic optimization:

// components/PostCard.tsx
import Image from 'next/image';
import { WPPostWithACF, WPFeaturedImage } from '@/lib/types';

interface Props {
  post: WPPostWithACF;
  image?: WPFeaturedImage;
}

export function PostCard({ post, image }: Props) {
  return (
    <article>
      {image && (
        <Image
          src={image.source_url}
          alt={image.alt_text || post.title.rendered}
          width={800}
          height={450}
          priority={false}
          sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
        />
      )}
      <h3>{post.title.rendered}</h3>
      <p>{post.excerpt.rendered}</p>
    </article>
  );
}

Use dynamic imports for heavy components to reduce initial JavaScript:

// app/blog/[slug]/page.tsx (updated)
import dynamic from 'next/dynamic';
const RelatedPosts = dynamic(() => import('@/components/RelatedPosts'), {
  loading: () => <p>Loading...</p>,
});

export default async function PostPage({ params }: { params: { slug: string } }) {
  const post = await getPost(params.slug);
  if (!post) notFound();

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

Sanitize WordPress HTML to prevent layout shifts from unstyled embeds or iframes. Use a library like sanitize-html:

// lib/sanitize.ts
import sanitize from 'sanitize-html';

export function sanitizeContent(html: string): string {
  return sanitize(html, {
    allowedTags: [
      'p', 'br', 'strong', 'em', 'u', 'a', 'h2', 'h3', 'h4', 'ul', 'ol', 'li',
      'blockquote', 'code', 'pre', 'img', 'iframe',
    ],
    allowedAttributes: {
      a: ['href', 'title'],
      img: ['src', 'alt', 'title', 'width', 'height'],
      iframe: ['src', 'width', 'height', 'frameborder', 'allow'],
    },
    transformTags: {
      img: (tagName, attribs) => {
        return {
          tagName: 'img',
          attribs: {
            ...attribs,
            loading: 'lazy',
          },
        };
      },
    },
  });
}

Set appropriate cache headers. Configure your hosting (Vercel, Netlify, or self-hosted) to cache static pages aggressively:

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  headers: async () => [
    {
      source: '/blog/:slug',
      headers: [
        {
          key: 'Cache-Control',
          value: 'public, s-maxage=3600, stale-while-revalidate=86400',
        },
      ],
    },
  ],
};

module.exports = nextConfig;

Preview Mode and Draft Content

Content teams need to preview posts before publishing. Headless WordPress requires an explicit preview flow.

Create a preview mode endpoint:

// app/api/preview/route.ts
import { NextRequest, NextResponse } from 'next/server';

const WP_API = process.env.NEXT_PUBLIC_WP_API_URL;
const PREVIEW_SECRET = process.env.PREVIEW_SECRET;

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const secret = searchParams.get('secret');
  const slug = searchParams.get('slug');

  if (secret !== PREVIEW_SECRET || !slug) {
    return NextResponse.json({ error: 'Invalid request' }, { status: 401 });
  }

  const res = await fetch(
    `${WP_API}/wp-json/wp/v2/posts?slug=${slug}&status=draft,publish`
  );
  if (!res.ok) {
    return NextResponse.json({ error: 'Post not found' }, { status: 404 });
  }

  const response = NextResponse.redirect(
    new URL(`/blog/${slug}`, request.url)
  );
  response.cookies.set('__previewMode', 'true', { maxAge: 3600 });
  response.cookies.set('__previewSlug', slug, { maxAge: 3600 });
  return response;
}

Modify your data-fetching to check for preview mode:

// lib/wordpress.ts (updated)
import { cookies } from 'next/headers';

export async function getPost(slug: string): Promise<WPPostWithACF | null> {
  const cookieStore = await cookies();
  const isPreview = cookieStore.get('__previewMode')?.value === 'true';
  const status = isPreview ? 'draft,publish,pending' : 'publish';

  const res = await fetch(
    `${WP_API}/wp-json/wp/v2/posts?slug=${slug}&status=${status}&_embed`,
    {
      next: { revalidate: isPreview ? 0 : 3600 },
      headers: isPreview
        ? { Authorization: `Bearer ${process.env.WP_AUTH_TOKEN}` }
        : {},
    }
  );
  if (!res.ok) return null;
  const posts: WPPostWithACF[] = await res.json();
  return posts[0] || null;
}

Generate a preview URL in WordPress and share it with content teams. They see draft content without it being public.

Multi-Language Support

Many publishing platforms serve multiple languages. Use Next.js internationalization with WordPress language taxonomies or plugins like WPML or Polylang.

Structure your routes by locale:

// app/[locale]/blog/[slug]/page.tsx
import { getPost } from '@/lib/wordpress';

export const dynamicParams = false;

export async function generateStaticParams() {
  const locales = ['en', 'ar', 'fr'];
  const { posts } = await getAllPosts(1, 50);

  return locales.flatMap((locale) =>
    posts.map((post) => ({
      locale,
      slug: post.slug,
    }))
  );
}

export default async function PostPage({
  params,
}: {
  params: { locale: string; slug: string };
}) {
  const post = await getPost(params.slug, params.locale);
  if (!post) notFound();
  return <article>{/* ... */}</article>;
}

Update your WordPress fetch to accept locale:

// lib/wordpress.ts (updated)
export async function getPost(
  slug: string,
  locale: string = 'en'
): Promise<WPPostWithACF | null> {
  const params = new URLSearchParams({
    slug,
    _embed: '',
  });

  if (locale !== 'en') {
    params.append('lang', locale);
  }

  const res = await fetch(
    `${WP_API}/wp-json/wp/v2/posts?${params}`,
    { next: { revalidate: 3600 } }
  );
  if (!res.ok) return null;
  const posts: WPPostWithACF[] = await res.json();
  return posts[0] || null;
}

Production Deployment Patterns

Deploying headless WordPress and Next.js requires orchestrating two separate services.

Separate Infrastructure: WordPress runs on one server or managed hosting (WP Engine, Kinsta). Next.js runs on a Node.js hosting platform (Vercel, Netlify, self-hosted). They communicate only via REST API over HTTPS.

Environment Variables: Secure your configuration:

# .env.local
NEXT_PUBLIC_WP_API_URL=https://wordpress.example.com
REVALIDATE_SECRET=your-random-secret-key
PREVIEW_SECRET=another-random-secret-key
WP_AUTH_TOKEN=your-wp-api-auth-token

Error Handling and Fallbacks: WordPress might be slow or unreachable. Implement timeouts and fallbacks:

// lib/wordpress.ts (updated)
const FETCH_TIMEOUT = 10000;

function withTimeout(promise: Promise<Response>, ms: number): Promise<Response> {
  return Promise.race([
    promise,
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('Fetch timeout')), ms)
    ),
  ]) as Promise<Response>;
}

export async function getPost(slug: string): Promise<WPPostWithACF | null> {
  try {
    const res = await withTimeout(
      fetch(`${WP_API}/wp-json/wp/v2/posts?slug=${slug}&_embed`),
      FETCH_TIMEOUT
    );
    if (!res.ok) return null;
    return await res.json();
  } catch (error) {
    console.error('WordPress API error:', error);
    return null;
  }
}

Monitoring: Track API response times, revalidation success, and 404 errors. Use tools like Sentry, DataDog, or New Relic to alert on WordPress downtime or API failures.

Database Backups: WordPress still uses a database. Implement automated backups and test recovery procedures regularly. Headless architecture maintains the same database reliability requirements as traditional WordPress.

Conclusion

Headless WordPress with Next.js and TypeScript delivers a modern publishing platform: content teams work independently in WordPress, engineers optimize frontends with Next.js, and both scale separately. ISR keeps content fresh without full rebuilds. TypeScript catches schema mismatches early. Core Web Vitals improve through Next.js Image, dynamic imports, and caching. Multi-language and preview modes round out a production-ready system.

The setup requires orchestrating two services and monitoring API dependencies, but the trade-off is worth it for publishing platforms that need flexibility, performance, and independent scaling. Start with a single post type, get ISR and preview mode working, then expand to custom fields, multi-language, and advanced content modeling.

What’s the difference between headless WordPress and traditional WordPress?

Traditional WordPress serves complete HTML pages from a single server. Headless WordPress only manages content as JSON via REST API; a separate frontend (Next.js in this case) handles rendering, caching, and delivery. Headless decouples content from presentation, enabling independent scaling and optimization.

How does ISR improve SEO compared to client-side rendering?

ISR pre-renders pages at build time and regenerates them in the background when content changes. Search engines always see complete HTML, improving crawlability and indexability. Client-side rendering requires JavaScript to run before content is visible, which slows crawling and can miss dynamic content. ISR gives you static performance with dynamic freshness.

Do I need to rewrite my WordPress theme?

No. Headless WordPress doesn’t use WordPress themes at all. WordPress only serves JSON from its REST API. You build a completely separate Next.js frontend. Existing WordPress plugins, custom post types, and ACF fields continue to work; you just query them as JSON instead of rendering them in PHP.

What happens if WordPress is down?

If WordPress is unreachable during a revalidation, ISR uses the last cached version. Users see slightly stale content but the site stays online. For critical failures, implement fallback pages or redirect to a status page. Monitor WordPress uptime and API response times to catch issues early.

Can I use headless WordPress for e-commerce or complex applications?

Headless WordPress works well for content-heavy sites: blogs, news, documentation, and publishing platforms. For e-commerce, consider a dedicated headless commerce platform like Shopify or Medusa. You can integrate both, but complex transactional logic is better handled by purpose-built systems.

Leave a Reply

Your email address will not be published. Required fields are marked *