storieasy-logo

How to Integrate Sanity CMS with Next.js for a Powerful Headless Experience

dhruvesh borad

Info

29 Apr 2025

|

25 min to read

sanity+next.js

Next.js

sanity

Handless CMS

serverless

In the modern web development world, content is king. But managing it efficiently is just as important. That’s where headless CMSs like Sanity.io and frameworks like Next.js come in. This blog will walk you through integrating Sanity with Next.js creating a scalable, SEO-friendly, and developer-friendly application.

What Is Sanity?

Sanity.io is a powerful headless CMS that offers real-time collaboration, customizable content structures, and excellent developer tools. It’s ideal for developers who want to control both the content model and the front end.

⚙️ Why Use Sanity with Next.js?

  • 🔄 Real-time data editing and preview
  • ⚡ Super-fast with Static Site Generation (SSG) and Incremental Static Regeneration (ISR)
  • 💾 Structured content with GROQ queries
  • 📦 Portable text for rich content rendering
  • 🌐 Headless — perfect for JAMstack apps

🧰 Prerequisites

Make sure you have the following before you begin:

  • Node.js and npm/yarn installed
  • Next.js project setup
  • Basic knowledge of React and API calls

Step-by-Step: Sanity + Next.js Integration

1. Set up a Sanity Studio

bashCopyEditnpm create sanity@latest

1npm create sanity@latest
  • Choose a project name.
  • Select the Blog (schema) template
  • Deploy using Sanity’s CLI
1sanity deploy

bashCopyEditsanity deploy

💡 You’ll get a Sanity Studio at a hosted URL.

2. Define Your Schema (e.g., post.js)

1export default {
2  name: 'post',
3  type: 'document',
4  title: 'Post',
5  fields: [
6    { name: 'title', type: 'string' },
7    { name: 'slug', type: 'slug', options: { source: 'title' } },
8    { name: 'body', type: 'blockContent' },
9    { name: 'mainImage', type: 'image' },
10  ]
11}
12

3. Connect Sanity in Next.js

Install the Sanity client:

1npm install @sanity/client @portabletext/react

Create a client file in lib/sanity.js:

1import { createClient } from '@sanity/client'
2
3export const client = createClient({
4  projectId: 'your_project_id',
5  dataset: 'production',
6  apiVersion: '2023-01-01',
7  useCdn: true
8})

4. Fetch Data Using GROQ

GROQ (Graph-Relational Object Queries) is Sanity's query language:

1const query = `*[_type == "post"]{title, slug, body, mainImage}`
2const posts = await client.fetch(query)

Use getStaticProps in pages/index.js:

1export async function getStaticProps() {
2  const posts = await client.fetch(`*[_type == "post"]`)
3  return { props: { posts } }
4}

5. Render Content with Portable Text

Install:

1npm install @portabletext/react
1import { PortableText } from '@portabletext/react'
2
3<PortableText value={post.body} />

6. Handle Images

1import imageUrlBuilder from '@sanity/image-url'
2
3const builder = imageUrlBuilder(client)
4const urlFor = (source) => builder.image(source)

Usage:

1<img src={urlFor(post.mainImage).width(600).url()} alt="Post image" />

7. Setup Dynamic Routing (e.g., [slug].js)

1export async function getStaticPaths() {
2  const posts = await client.fetch(`*[_type == "post"]{slug}`)
3  return {
4    paths: posts.map((post) => ({ params: { slug: post.slug.current } })),
5    fallback: 'blocking',
6  }
7}

8. Enable Preview Mode (Optional but Recommended)

Sanity supports live preview of draft content. You can configure preview mode using environment variables and secure preview tokens.

Advanced Tips for Sanity + Next.js

Once you’ve integrated Sanity with Next.js, there are several advanced strategies to take your project to the next level, ensuring both performance and scalability for production-ready applications.

1. Optimize Images with Next.js Image Component

Sanity stores high-resolution images, but loading them directly can slow down your site. Combine Sanity with Next.js <Image /> to:

  • Serve responsive images automatically
  • Use lazy loading for below-the-fold content
  • Enable WebP or AVIF formats for faster performance

Example:

1import Image from "next/image";
2import { urlFor } from "../lib/sanity";
3
4<Image
5  src={urlFor(post.mainImage).url()}
6  alt={post.title}
7  width={800}
8  height={500}
9  priority={true}
10/>

This ensures your blog or marketing site loads quickly, improving SEO and user experience.

2. Incremental Static Regeneration (ISR)

With ISR, your Next.js pages update automatically when new content is added in Sanity without a full redeploy. This is perfect for blogs, portfolios, and marketing sites.

Example:

1export async function getStaticProps() {
2  const posts = await client.fetch(`*[_type == "post"]`);
3  return {
4    props: { posts },
5    revalidate: 60, // Update every 60 seconds
6  };
7}

Benefits of ISR:

  • Faster page loads (static pages served via CDN)
  • Automatic content refresh without downtime
  • Better Core Web Vitals scores for SEO

3. Real-Time Preview Mode

Sanity’s real-time preview allows editors to see draft content instantly in your Next.js front end. This is crucial for teams working on marketing campaigns or dynamic blogs.

  • Configure preview tokens in .env.local
  • Fetch draft content when preview mode is active
  • Toggle between draft and published content seamlessly

This makes content updates frictionless and ensures your editors have confidence before publishing live content.

4. Multi-Language and Localization Support

Sanity makes it easy to structure content for multiple languages:

  • Define a locale field in your schema
  • Use GROQ queries to fetch content based on the visitor’s language
  • Combine with Next.js dynamic routing for example.com/en and example.com/es

This approach is essential for global brands, travel blogs, and international portfolios.

5. Automating Revalidation with Webhooks

When using ISR, you can configure Sanity webhooks to automatically trigger page revalidation whenever content is updated. This ensures visitors always see the latest version without waiting for the next ISR cycle.

Steps:

  1. Go to Sanity Studio → Project Settings → API → Webhooks
  2. Add your Next.js revalidation endpoint
  3. Test by publishing new content

Result: Real-time content updates + optimal performance.

6. Security Best Practices

  • Store API tokens securely in .env.local
  • Avoid exposing sensitive keys on the client side
  • Use Sanity’s read-only client for public data fetching
  • Regularly rotate tokens and restrict scopes

Security is crucial for e-commerce sites, SaaS apps, and multi-author blogs.

7. SEO Best Practices for Sanity + Next.js

Integrate SEO from the start:

  • Use <Head> from next/head to add meta titles, descriptions, and Open Graph tags
  • Use Sanity fields for dynamic SEO content per page/post
  • Optimize URLs, slugs, and headings for readability
  • Include structured data (JSON-LD) for rich results

Example:

1<Head>
2  <title>{post.title} | My Blog</title>
3  <meta name="description" content={post.description} />
4  <meta property="og:title" content={post.title} />
5  <meta property="og:description" content={post.description} />
6</Head>

SEO ensures your content ranks higher, increases organic traffic, and makes your Sanity-powered site fully monetizable.

8. Scaling Your Sanity + Next.js Project

  • Modular Schemas: Break content into reusable modules (text blocks, hero sections, galleries)
  • Component-Driven Development: Map Sanity content types to React components for flexibility
  • Edge Deployments: Use Vercel or Netlify for global CDN delivery and super-fast load times

This setup is future-proof for blogs, e-commerce, or enterprise-level websites.

🎯 Real-World Use Cases

  • Blogs with real-time content updates
  • Marketing websites
  • Portfolios with dynamic CMS control
  • Multi-language websites

Tips for Production

  • Enable image optimization with Next.js
  • Use ISR for frequent content updates
  • Secure API tokens via .env.local
  • Use Sanity’s webhooks to trigger revalidation

Conclusion

Combining Next.js and Sanity.io gives you an unmatched combination of performance, flexibility, and developer experience. Whether you're building a blog, e-commerce site, or marketing platform, this duo sets you up for long-term success.

Want to build modern, scalable, and content-rich web applications? Start integrating Sanity with Next.js today!

Subscribe to our Newsletter

Provide your email to get email notification when we launch new products or publish new articles

email

Share with your friends: