Prompt
How do I connect a headless CMS to Next.js?
Latest observation
Oct 20, 2026
OpenAI APIWeb search: off
Connecting a headless CMS to Next.js usually means:
- Choose a CMS
- Fetch content from its API
- Render that content in Next.js
- 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:
revalidatefor 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
zodif 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.