.Env.Local File Configuration not working with Next.js Application
This is a common issue when setting up Sanity with Next.js! The problem is that Next.js and Sanity Studio have different prefixing requirements for environment variables.
Here's what's happening:
In Next.js applications, environment variables need to be prefixed with NEXT_PUBLIC_ to be exposed to the browser/client-side code. When you're configuring your Sanity client in a Next.js app, you need:
NEXT_PUBLIC_SANITY_PROJECT_ID=your-project-id NEXT_PUBLIC_SANITY_DATASET=production
Then access them like this:
// sanity.config.js or your client configuration
export default defineConfig({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
// other configuration
})If you're configuring Sanity Studio itself (not just the client in Next.js), the variables need the SANITY_STUDIO_ prefix instead:
SANITY_STUDIO_API_PROJECT_ID=your-project-id SANITY_STUDIO_API_DATASET=production
Common mistakes:
- Using
SANITY_STUDIO_prefix in a Next.js app (won't work - Next.js doesn't recognize this prefix) - Forgetting the
NEXT_PUBLIC_prefix (variables won't be available in browser code) - Not restarting the dev server after adding/changing
.env.local(Next.js only reads these on startup)
Solution: Make sure you're using NEXT_PUBLIC_ prefix in your .env.local file and restart your Next.js dev server. According to the Sanity documentation on environment variables, project IDs and dataset names are not secret and will be exposed in your built application anyway, so using NEXT_PUBLIC_ is safe here.
If you need server-side only variables (like API tokens), you can use unprefixed variables in API routes or server components, but for the Sanity client configuration that runs in the browser, you need the NEXT_PUBLIC_ prefix.
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.