Error when creating a client in Next.js with Sanity.io integration
This error message is a bit misleading! The error mentions options from @sanity/preview-kit/client, but based on your code, you're not actually using any of those options. This error typically occurs due to a version mismatch or caching issue with your dependencies.
Here are the steps to fix this:
1. Check your dependencies
First, make sure you have the correct versions installed. For Next.js 13 with Sanity v3, you should be using:
npm install next-sanity@latest @sanity/client@latestOr if you're using yarn:
yarn add next-sanity@latest @sanity/client@latest2. Clear your cache
After updating, clear your Next.js cache and node_modules:
rm -rf .next node_modules package-lock.json
npm install3. Verify your client code
Your client configuration looks correct for basic usage. However, a couple of notes:
Token exposure: You're using
NEXT_PUBLIC_SANITY_EDITORwhich exposes the token to the browser. If this is a write token, you should not use theNEXT_PUBLIC_prefix as this makes it publicly accessible. Only use public tokens for client-side code, and keep write tokens server-side only.Better approach: Create separate clients for server and client usage:
// lib/sanity.client.ts
import { createClient } from 'next-sanity'
import { apiVersion, dataset, projectId, useCdn } from '../env'
// Public client (for client-side)
export const client = createClient({
apiVersion,
dataset,
projectId,
useCdn,
})
// Server client with token (for server-side only)
export const serverClient = createClient({
apiVersion,
dataset,
projectId,
useCdn: false, // Don't use CDN for writes
token: process.env.SANITY_API_TOKEN, // No NEXT_PUBLIC_ prefix!
})4. If you need preview/draft mode
If you're trying to set up preview mode (which might be why the error mentions preview-kit), you should use the Live Content API for modern Next.js applications, or if you specifically need the older preview-kit approach, you'd import from a different package:
import { createClient } from '@sanity/preview-kit/client'But for your basic setup, stick with next-sanity's createClient.
After following these steps, restart your dev server and the error should be resolved. If you're still seeing issues, double-check that you don't have any conflicting imports or multiple versions of Sanity packages installed by running npm ls next-sanity and npm ls @sanity/client.
Sanity β Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.