Sanity CMS with Next.js — Setup & Visual Editing Guide
Integrate Sanity CMS with Next.js — Studio configuration, optimized GROQ queries, draft mode, and real-time visual editing with live previews.

Sanity is a structured-content platform, not a rendering engine — it hands you JSON, and Next.js does the rendering. That separation is powerful, but it means query design, caching, and preview wiring are all your responsibility. This guide sets up a production Sanity + Next.js integration end to end, including real-time visual editing.
Step 1: Install Sanity and Embed the Studio
Visiting /studio now serves the full Sanity Studio editor inside your Next.js app — no separate deployment or hosting needed.
Step 2: Define a Schema
Step 3: Write Efficient GROQ Queries
The most common Sanity performance mistake is fetching entire documents when a page only renders a few fields. Use projections instead.
defineQuery gives you fully typed query results (via the Sanity TypeGen CLI) instead of unknown, and the explicit projection means the listing query never pulls the full rich-text body field it doesn't need.
Step 4: Fetch Content with Caching
Tag the fetch with "posts" so a Sanity webhook can call revalidateTag("posts") the moment content is published — you get near-instant cache invalidation without polling.
Step 5: Set Up Real-Time Visual Editing
Sanity's Presentation tool lets editors click directly on rendered content in an iframe and jump straight to the matching field in Studio — but it requires draft mode wired up first.
With perspective: "drafts" active only when draftMode().isEnabled is true, editors previewing through Presentation see unpublished changes instantly, while every regular visitor still gets the cached, published version.
Key Takeaways
Embedding Sanity Studio inside your Next.js app removes the need for separate hosting, tight GROQ projections keep queries fast by avoiding over-fetching, and pairing Next.js draft mode with Sanity's Presentation tool is what turns a normal blog into a click-to-edit visual editing experience — with published content still served from cache for everyone else.






