Accessing Sanity environment variables from Next.js outside studio
The modern approach is to use environment variables with Next.js, and you don't need to access sanity.json from your Next.js code at all. Here's how to set this up properly:
Using Environment Variables in Next.js
Create a .env.local file in your Next.js project root (not in the Studio directory):
NEXT_PUBLIC_SANITY_PROJECT_ID=your-project-id
NEXT_PUBLIC_SANITY_DATASET=productionThe NEXT_PUBLIC_ prefix is important - it tells Next.js to expose these variables to the browser.
Then update your client configuration:
// lib/sanity.js or client.js
import { createClient } from '@sanity/client'
// or if using next-sanity:
// 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: '2024-01-01', // use current date
useCdn: true, // set to false if you need fresh data
})For Production (Netlify)
In your Netlify dashboard, add the same environment variables:
- Go to Site Settings → Environment Variables
- Add
NEXT_PUBLIC_SANITY_PROJECT_IDwith your project ID - Add
NEXT_PUBLIC_SANITY_DATASETwithproduction(or your production dataset name)
This way, your local development uses the values from .env.local, while your Netlify deployment uses the values from Netlify's environment settings. You can even set different values for different Netlify deploy contexts (production, preview, etc.).
Modern Approach with next-sanity
If you're starting fresh or can update, I'd recommend using the next-sanity package, which is the official toolkit for Next.js integration. When you run sanity init in a Next.js project, it automatically sets up environment variables and creates a properly configured client for you.
The key insight is that sanity.json is a Studio v2 configuration file that's separate from your Next.js app - you don't need to access it from Next.js. Environment variables are the clean, standard way to configure your Sanity client for different environments.
Show original thread1 reply
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.