Headless CMS Integration Blueprint for Next.js App Router
This blueprint provides a production-ready architecture for integrating a headless CMS (using Sanity as the example, but adaptable to Contentful, Strapi, etc.) with Next.js 14+ App Router . It emphasizes:
Incremental Static Regeneration (ISR) : Static pages regenerate on-demand via webhooks or time-based revalidation.
Preview Flows : Secure draft/preview mode with token-based auth.
Performance : Edge-optimized fetching, caching, and parallel routes.
Scalability : On-demand revalidation for dynamic routes like /blog/[slug].
Architecture Overview
code Copy code
[Sanity Studio/Dashboard]
├── Webhooks (on publish/unpublish) → POST /api/revalidate
└── GROQ Queries → Next.js API Routes/Lib Client
[Next.js App Router]
├── app/ (Static + ISR Pages)
│ ├── layout.tsx (Root Layout + Providers)
│ ├── page.tsx (Home - ISR)
│ └── [slug]/page.tsx (Dynamic ISR Routes)
├── lib/sanity.ts (GROQ Client + Types)
├── middleware.ts (Preview Token Validation)
├── api/revalidate/route.ts (Webhook Handler)
└── api/preview/route.ts (Token Generation)
[Deployment: Vercel/Netlify]
├── ISR: Automatic edge revalidation
├── Preview: Cookie-based session
└── Caching: Next.js fetch() + revalidateTag/Path
Key Flows :
Build/Static Gen : generateStaticParams + ISR (export const revalidate = 3600).
Preview : User logs in → Token cookie → Bypass cache → Fetch drafts.
Update Content : Publish in CMS → Webhook → revalidatePath('/blog/[slug]').
Fallback : Dynamic rendering if no static params.
Prerequisites
Next.js 14.2+ project: npx create-next-app@latest --app.
Sanity project: Create Studio → Install @sanity/webhook template.
Node.js 20+.
Step 1: Install Dependencies
bash Copy code
npm install next@latest react@latest react-dom@latest
npm install @sanity/client @sanity/webhook @sanity/image-url
npm install -D @types/node typescript @types/react @types/react-dom
npm install groq # For type-safe queries
Step 2: Environment Variables
.env.local:
code Copy code
SANITY_PROJECT_ID=your_project_id
SANITY_DATASET=production # or 'preview' for drafts
SANITY_API_VERSION=2024-03-20
SANITY_TOKEN=sk... # Write token for webhooks
NEXT_PUBLIC_SANITY_PROJECT_ID=your_project_id # Public reads
PREVIEW_SECRET=your_random_secret # For token validation
Step 3: Sanity Client Setup (lib/sanity.ts)
Type-safe GROQ client with preview support.
typescript Copy code
import { createClient, groq } from 'next-sanity'
import imageUrlBuilder from '@sanity/image-url'
import { Post } from '@/types/post' // Define your schema types
export const client = createClient({
projectId: process.env.SANITY_PROJECT_ID!,
dataset: process.env.SANITY_DATASET!,
useCdn: process.env.NODE_ENV === 'production', // CDN for prod reads
apiVersion: process.env.SANITY_API_VERSION,
token: process.env.SANITY_TOKEN, // Only server-side
})
const clientForPreview = createClient({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
dataset: 'draft', // Preview dataset
useCdn: false,
apiVersion: process.env.SANITY_API_VERSION,
perspective: 'previewDrafts',
})
const builder = imageUrlBuilder(client)
export function urlForImage(source: any) {
return builder.image(source)
}
// Typed GROQ Queries
export async function getPosts(): Promise<Post[]> {
return client.fetch(groq`*[_type == "post"] | order(publishedAt desc) {
_id, title, slug, publishedAt, body[] { ..., asset-> }
}`, {}, { cache: 'no-store', next: { tags: ['posts'] } })
}
export async function getPost(slug: string): Promise<Post> {
return client.fetch(groq`*[_type == "post" && slug.current == $slug][0] {
_id, title[], slug, publishedAt, body[]
}`, { slug }, { cache: 'no-store', next: { tags: ['post', `post-${slug}`] } })
}
Types (types/post.ts):
typescript Copy code
export interface Post {
_id: string
title: string[]
slug: { current: string }
publishedAt: string
body: any[]
}
Step 4: ISR Pages
Home Page (app/page.tsx) - Time-based ISR
typescript Copy code
import { getPosts } from '@/lib/sanity'
export const revalidate = 3600 // 1 hour
export default async function Home() {
const posts = await getPosts()
return (
<div>
<h1>Blog</h1>
<ul>
{posts.map((post) => (
<li key={post._id}>
<a href={`/blog/${post.slug.current}`}>{post.title[0]}</a>
</li>
))}
</ul>
</div>
)
}
Dynamic Route (app/blog/[slug]/page.tsx) - On-Demand ISR
typescript Copy code
import { getPost, client } from '@/lib/sanity'
import { notFound } from 'next/navigation'
type Props = { params: { slug: string } }
export async function generateStaticParams() {
const posts = await client.fetch(groq`*[_type == "post"]{ slug }`)
return posts.map((post: any) => ({ slug: post.slug.current }))
}
export const revalidate = false // On-demand only
export default async function PostPage({ params }: Props) {
const post = await getPost(params.slug)
if (!post) notFound()
return (
<article>
<h1>{post.title[0]}</h1>
<div>{/* Render post.body with Portable Text */}</div>
</article>
)
}
Step 5: Preview Flows
Middleware (middleware.ts) - Token Validation
typescript Copy code
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { createClient } from '@/lib/sanity' // Preview client
export function middleware(request: NextRequest) {
const token = request.cookies.get('sanity-preview-token')?.value
const preview = request.cookies.get('sanity-preview')?.value === 'true'
if (preview && !token) {
return NextResponse.redirect(new URL('/', request.url))
}
// Optional: Validate token against Sanity (server-side)
return NextResponse.next({
request: {
headers: new Headers({
...Array.from(request.headers.entries()),
'x-is-preview-mode': preview ? 'true' : 'false',
'x-preview-token': token || '',
}),
},
})
}
export const config = { matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)' }
Preview Button (app/blog/[slug]/page.tsx - Add Preview Link)
In Sanity Studio, add a custom preview URL: https://yoursite.com/blog/{{slug.current}}?preview=true.
Client-side toggle (use usePreview hook or cookies):
typescript Copy code
'use client'
import { useEffect } from 'react'
import { useSearchParams } from 'next/navigation'
export function PreviewBanner({ post }: { post: Post }) {
const searchParams = useSearchParams()
const isPreview = searchParams.get('preview') === 'true'
useEffect(() => {
if (isPreview) {
document.cookie = 'sanity-preview=true; path=/; max-age=3600'
// Fetch /api/preview to set token
}
}, [])
return isPreview ? <div>Preview Mode • <a href="/api/exit-preview">Exit</a></div> : null
}
Token Endpoint (app/api/preview/route.ts)
typescript Copy code
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { clientForPreview } from '@/lib/sanity'
export async function GET() {
const secret = req.nextUrl.searchParams.get('secret')
if (secret !== process.env.PREVIEW_SECRET) {
return new Response('Unauthorized', { status: 401 })
}
// Validate token with Sanity (optional)
cookies().set('sanity-preview-token', process.env.SANITY_TOKEN!, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 3600,
path: '/',
})
cookies().set('sanity-preview', 'true', { maxAge: 3600, path: '/' })
redirect('/blog') // Redirect to home or intended page
}
Exit Preview (app/api/exit-preview/route.ts):
typescript Copy code
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export async function GET() {
cookies().delete('sanity-preview')
cookies().delete('sanity-preview-token')
redirect('/')
}
Preview-Aware Data Fetching
Override in preview mode:
typescript Copy code
// In getPost()
const isPreview = headers().get('x-is-preview-mode') === 'true'
const previewClient = isPreview ? clientForPreview : client
return previewClient.fetch(...)
Step 6: ISR Webhooks (app/api/revalidate/route.ts)
Sanity webhook → Revalidate paths/tags.
typescript Copy code
import { revalidatePath, revalidateTag } from 'next/cache'
import { NextRequest, NextResponse } from 'next/server'
import { WebhookPayload } from '@sanity/client' // Or custom
export async function POST(req: NextRequest) {
const payload: WebhookPayload = await req.json()
const token = req.headers.get('Authorization')?.replace('Bearer ', '')
if (token !== process.env.SANITY_TOKEN) {
return NextResponse.json({ message: 'Unauthorized' }, { status: 401 })
}
// Handle publish/unpublish/delete
if (payload._type === 'post') {
const slug = payload.slug?.current
if (slug) {
revalidatePath(`/blog/${slug}`)
revalidateTag(`post-${slug}`)
}
}
revalidatePath('/blog') // Invalidate list
revalidateTag('posts')
return NextResponse.json({ revalidated: true })
}
Sanity Webhook Setup :
Studio → Manage → Webhooks → New.
URL: https://yoursite.com/api/revalidate.
Events: publish, unpublish, delete.
HTTP Headers: Authorization: Bearer ${SANITY_TOKEN}.
Step 7: Advanced Optimizations
Parallel Routes : @posts slot for loading states.
Streaming : <Suspense> for lazy post bodies.
Images : next/image with urlForImage.
Search Params ISR : export async function generateStaticParams({ searchParams }) { ... }.
Tags : Granular revalidation, e.g., next.revalidateTag('category-tech').
Deployment Checklist
Platform Notes Vercel Auto-deploys ISR/webhooks. Edge Middleware. Set env vars. Netlify Functions for API routes. Edge Handlers for middleware. Custom PM2/Docker for Node server. Redis for custom caching.
Testing :
Local: npm run dev → Preview via /api/preview?secret=....
ISR: Publish post → Check headers x-next-revalidated-token.
Preview: Inspect cookies, verify draft content.
This blueprint scales to 100k+ pages. Adapt GROQ queries to your schema. For other CMS: Replace client with GraphQL/REST fetchers. Questions? Provide your CMS/schema!