Prompt

How do I connect a headless CMS to Next.js?

Technology / Developer Tools1 observationLast seen Oct 20, 2026

Latest observation

Oct 20, 2026OpenAI APIWeb search: off

Connecting a headless CMS to Next.js usually means:

  1. Choose a CMS
  2. Fetch content from its API
  3. Render that content in Next.js
  4. Handle updates via revalidation/webhooks if needed

Basic setup

1) Get your CMS API details

Most headless CMSs give you:

  • an API endpoint
  • an access token or API key
  • content types/collections (posts, pages, authors, etc.)

Examples: Contentful, Sanity, Strapi, Prismic, Storyblok, Payload, Directus.


2) Fetch content in Next.js

If you use the App Router (app/)

Fetch data directly in Server Components:

// app/page.tsx
async function getPosts() {
  const res = await fetch("https://api.example-cms.com/posts", {
    headers: {
      Authorization: `Bearer ${process.env.CMS_TOKEN}`,
    },
    next: { revalidate: 60 }, // cache for 60s
  });

  if (!res.ok) throw new Error("Failed to fetch posts");
  return res.json();
}

export default async function HomePage() {
  const posts = await getPosts();

  return (
    <main>
      <h1>Posts</h1>
      <ul>
        {posts.map((post: any) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </main>
  );
}

If you use the Pages Router (pages/)

Use getStaticProps or getServerSideProps:

// pages/index.tsx
export async function getStaticProps() {
  const res = await fetch("https://api.example-cms.com/posts");
  const posts = await res.json();

  return {
    props: { posts },
    revalidate: 60,
  };
}

3) Store secrets in environment variables

CMS_TOKEN=your_token_here
CMS_API_URL=https://api.example-cms.com

Then access them in code:

process.env.CMS_API_URL
process.env.CMS_TOKEN

4) Render rich content

If your CMS returns markdown or portable text/rich text:

  • use a markdown renderer
  • use the CMS’s rich text renderer
  • sanitize if content is user-generated

Example with markdown:

import ReactMarkdown from "react-markdown";

export default function Post({ content }: { content: string }) {
  return <ReactMarkdown>{content}</ReactMarkdown>;
}

5) Keep content fresh

Use one of these:

  • revalidate for periodic regeneration
  • webhooks from the CMS to trigger Next.js revalidation
  • SSR if content must always be fresh

Example webhook route in App Router:

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

export async function POST(req: NextRequest) {
  const { secret, path } = await req.json();

  if (secret !== process.env.REVALIDATE_SECRET) {
    return NextResponse.json({ message: "Invalid secret" }, { status: 401 });
  }

  revalidatePath(path);
  return NextResponse.json({ revalidated: true });
}

Common patterns

Static pages from CMS

Good for:

  • blogs
  • docs
  • marketing pages

Use:

  • generateStaticParams()
  • revalidate
  • CMS webhooks

Dynamic pages

Good for:

  • dashboards
  • user-specific content
  • frequently changing data

Use:

  • server-side fetching
  • route handlers
  • client-side fetching if needed

Example: blog post by slug

// app/blog/[slug]/page.tsx
async function getPost(slug: string) {
  const res = await fetch(`${process.env.CMS_API_URL}/posts/${slug}`, {
    headers: {
      Authorization: `Bearer ${process.env.CMS_TOKEN}`,
    },
    next: { revalidate: 60 },
  });

  if (!res.ok) return null;
  return res.json();
}

export default async function PostPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const post = await getPost(slug);

  if (!post) return <div>Post not found</div>;

  return (
    <article>
      <h1>{post.title}</h1>
      <div>{post.body}</div>
    </article>
  );
}

Tips

  • Prefer server-side fetching for private API keys
  • Use ISR/revalidation for performance
  • Add types/interfaces for CMS data
  • Validate CMS responses with zod if reliability matters
  • Avoid exposing secrets to client components

If you want, I can show you a full example for a specific CMS like Contentful, Sanity, Strapi, or Prismic.

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (1 observation for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.