Sanity Visual Editing with Next.js App Router: Setup and Troubleshooting

Shahadat Hossain
Software Developer
Sanity Visual Editing with Next.js App Router: Setup and Troubleshooting
Sanity Visual Editing connects your CMS directly to your website preview, allowing editors to see how content appears in its actual frontend context and navigate from rendered content back to the corresponding Studio fields.
Instead of repeatedly publishing content to check its appearance, editors can work with draft content, inspect the rendered result, and make changes through an integrated preview experience.
This guide explains how to integrate Sanity Visual Editing with Next.js App Router, covering the Presentation Tool, Draft Mode, live content updates, Content Source Maps, Stega encoding, and common configuration issues.
01. Understanding Visual Editing
A traditional headless CMS separates content management from frontend presentation. Editors work with structured fields inside the CMS, while the website renders those values through its own components and layouts.
Although this separation provides flexibility, it can make content editing less intuitive. Editors may understand what a field contains without knowing exactly how it will appear on the website.
Visual Editing addresses this gap by connecting Sanity Studio with the actual frontend preview.
The workflow becomes:
Edit → Preview → Inspect → Select → Edit the source field
Through the Presentation Tool, the frontend is displayed inside an iframe. Editors can inspect draft content in its rendered context and use click-to-edit overlays to navigate to the corresponding fields in Studio.
This workflow builds on several Sanity capabilities:
- Draft Mode: Allows the frontend to retrieve unpublished content for preview.
- Perspectives: Determines which version of content is returned, such as published or draft content.
- Content Source Maps: Connects rendered content back to its originating Sanity documents and fields.
- Stega encoding: Embeds invisible metadata into supported string values so Visual Editing can identify their source.
- Live Content API: Delivers content updates without requiring manual page refreshes.
These capabilities work together to connect the CMS editing experience with the rendered website.
02. How Visual Editing Works
The integration involves two applications: Sanity Studio and the Next.js frontend.
The Presentation Tool loads the frontend preview inside an iframe. When an editor opens the preview, Studio communicates with the frontend's Draft Mode endpoint to establish a preview session.
Once Draft Mode is enabled, the frontend can retrieve draft content using the appropriate perspective and server-side credentials.
The content is then rendered with the metadata required for Visual Editing. The VisualEditing component reads that information and provides overlays that allow editors to select rendered content and navigate to its corresponding Studio field.
The Live Content API handles content updates separately. SanityLive subscribes to changes and updates the frontend when relevant content changes.
The overall flow is:
Studio → Presentation Tool → Frontend iframe → Draft Mode → Draft-aware fetching → Rendered content → Visual Editing overlays
Live content updates flow through SanityLive and refresh the relevant frontend content.
03. Implementation
3.1. Configure the Sanity client
Start by creating a shared Sanity client that contains the project configuration used throughout the application.
The stega.studioUrl option identifies the Studio location that should receive click-to-edit navigation.
// src/sanity/lib/client.ts
import {createClient} from 'next-sanity'
export const client = createClient({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!,
apiVersion: '2026-02-01',
useCdn: true,
stega: {
studioUrl: 'http://localhost:3333',
},
})For production, replace the local Studio URL with the deployed Studio URL.
The project ID and dataset are public configuration values. The API token should remain server-side and must not be exposed through a public environment variable.
3.2. Configure the Live Content API
The defineLive helper from next-sanity/live provides two important exports:
- sanityFetch for draft-aware content fetching.
- SanityLive for receiving real-time content updates.
// src/sanity/lib/live.ts
import {defineLive} from 'next-sanity/live'
import {client} from './client'
export const {sanityFetch, SanityLive} = defineLive({
client,
serverToken: process.env.SANITY_API_READ_TOKEN,
browserToken: process.env.SANITY_API_READ_TOKEN,
})The server token is used for server-side content fetching, including access to drafts during preview sessions.
The browser token supports live updates in the browser. Because it is exposed to client-side code when used, it must have only the minimum permissions required. A Viewer-only token is appropriate for this purpose.
Although the same token can be used for both configurations, keeping the two roles conceptually separate makes the security boundary easier to understand.
3.3. Enable and disable Draft Mode
Draft Mode connects the Studio preview session to the Next.js application.
The enable endpoint uses defineEnableDraftMode from next-sanity/draft-mode. It handles the preview activation flow and verifies the request using the configured Sanity client.
// src/app/api/draft-mode/enable/route.ts
import {client} from '@/sanity/lib/client'
import {defineEnableDraftMode} from 'next-sanity/draft-mode'
export const {GET} = defineEnableDraftMode({
client: client.withConfig({
token: process.env.SANITY_API_READ_TOKEN,
}),
})To exit preview mode, create a separate disable endpoint.
// src/app/api/draft-mode/disable/route.ts
import {draftMode} from 'next/headers'
import {NextRequest, NextResponse} from 'next/server'
export async function GET(request: NextRequest) {
;(await draftMode()).disable()
return NextResponse.redirect(new URL('/', request.url))
}This endpoint disables Draft Mode for the current session and redirects the visitor to the homepage.
The disable route should remain a controlled preview-exit operation. Avoid using it as a general-purpose endpoint for changing authentication or authorization state.
3.4. Configure the Presentation Tool
The Presentation Tool connects Sanity Studio to the frontend preview.
Configure the preview origin and the endpoint used to enable Draft Mode.
// sanity.config.ts
import {presentationTool} from 'sanity/presentation'
import {resolve} from './src/presentation/resolve'
presentationTool({
resolve,
previewUrl: {
origin: 'http://localhost:3000',
previewMode: {
enable: '/api/draft-mode/enable',
},
},
})The origin should point to the Next.js application.
For local development, this might be http://localhost:3000. For production, it should point to the deployed frontend.
The preview configuration and Draft Mode endpoint must match the actual frontend deployment.
3.5. Define document locations
Document locations tell the Presentation Tool where a Sanity document appears on the frontend.
For example, a blog post may be displayed at /posts/[slug]. The resolver maps the document's slug to that route.
// src/presentation/resolve.ts
import {defineLocations} from 'sanity/presentation'
export const resolve = {
locations: {
post: defineLocations({
select: {
title: 'title',
slug: 'slug.current',
},
resolve: (doc) => ({
locations: [
{
title: doc?.title,
href: `/posts/${doc?.slug}`,
},
],
}),
}),
},
}The resolver is important because it connects a Studio document to its corresponding frontend location.
Without a valid document location, Studio cannot reliably navigate the preview to the page associated with the selected document.
For applications with multiple document types, define locations for each type that has a corresponding frontend route.
3.6. Add Visual Editing and live updates to the root layout
The root layout is where the Visual Editing and live-update components are connected to the Next.js application.
SanityLive should be rendered so the application can receive live content updates.
VisualEditing should only be rendered while Draft Mode is active.
// src/app/layout.tsx
import {draftMode} from 'next/headers'
import {VisualEditing} from 'next-sanity/visual-editing'
import {SanityLive} from '@/sanity/lib/live'
export default async function RootLayout({
children,
}: {
children: React.ReactNode
}) {
const {isEnabled} = await draftMode()
return (
<html lang="en">
<body>
{children}
<SanityLive />
{isEnabled && <VisualEditing />}
</body>
</html>
)
}This separates the responsibilities of the two components.
SanityLive supports content synchronization, while VisualEditing provides the click-to-edit experience during preview sessions.
04. Environment and Configuration
The integration depends on a small number of environment variables.
| Variable | Purpose | Exposure |
|---|---|---|
NEXT_PUBLIC_SANITY_PROJECT_ID | Sanity project identifier | Public |
NEXT_PUBLIC_SANITY_DATASET | Dataset identifier | Public |
SANITY_API_READ_TOKEN | Draft fetching and live content access |
The read token needs the appropriate Viewer permission to retrieve draft content and support the configured live-update integration.
The browser token deserves particular attention. Any token passed to browser-side functionality must be treated as public, regardless of whether it originated from a server environment variable.
Configure Sanity CORS
The frontend origin must be allowed in the Sanity project's CORS configuration.
For local development, add the actual frontend origin, such as:
http://localhost:3000
For production, add the deployed frontend origin.
Enable Allow credentials for the relevant origin when required by the integration.
A missing or incorrect CORS configuration can prevent the browser from communicating with Sanity, resulting in failed live updates or 403 responses.
Make sure the configured origins match the actual URLs used by the Studio and frontend.
05. Common Issues and Troubleshooting
Visual Editing depends on several connected configuration points. A problem in one area can affect the entire preview workflow.
| Symptoms | Likely cause |
|---|---|
Preview iframe does not load | Incorrect preview origin, CORS configuration, or Draft Mode route |
Overlays are not clickable | Missing or incorrect stega.studioUrl, or missing source-map metadata |
Document does not navigate to preview | Missing or incorrect document location resolver |
Draft content is not visible | Draft Mode is inactive, token permissions are insufficient, or perspective configuration is incorrect |
Live updates do not arrive | SanityLive, browser token, or CORS configuration problem |
Keep configuration URLs synchronized
One common source of integration problems is inconsistent URLs.
The following configuration values must refer to the correct environments:
- Presentation Tool preview origin.
- Draft Mode enable endpoint.
- Studio URL in stega.studioUrl.
- Document location resolver URLs.
- Sanity CORS origins.
For example, using a production Studio URL in one configuration while retaining a local preview origin in another can cause navigation and preview issues.
Treat local development and production as separate configurations, and verify each one independently.
Handle Stega-encoded strings carefully
Stega encoding adds invisible metadata to supported string values.
These characters help Visual Editing identify the source of rendered content, but they can cause unexpected behavior when strings are used outside their intended presentation context.
For example, comparisons, URL construction, metadata generation, and certain data-processing operations should use clean values.
Use stega: false where clean strings are required, or remove Stega encoding before performing operations that depend on exact string values.
06. Final Considerations
Sanity Visual Editing provides a more direct relationship between structured CMS content and its frontend presentation.
The Presentation Tool connects Studio to the website, Draft Mode enables unpublished content previews, Content Source Maps and Stega encoding support click-to-edit navigation, and the Live Content API keeps the preview synchronized with content changes.
However, a reliable integration depends on keeping the configuration consistent across both applications.
Before considering the setup complete, verify that:
- The frontend preview loads inside the Presentation Tool.
- Draft content is visible without publishing.
- Clicking rendered content navigates to the correct Studio field.
- Changes appear in the preview without a manual refresh.
- Metadata and route parameters contain clean values.
- Browser-exposed tokens have only the required permissions.
- Local and production URLs and CORS origins are configured correctly.
Visual Editing is available across Sanity plans, while Live Content API usage is subject to the limits of the applicable plan.
For new integrations, check the current next-sanity compatibility requirements and Sanity documentation before choosing package versions or copying configuration examples.
The most important lesson is that Visual Editing is not a single component added to a frontend. It is an integration between content fetching, preview authentication, document resolution, metadata handling, and live synchronization. Each part must work together to deliver a dependable editing experience.
