Why isn't my Sanity config reading projectId from .env.local in Next.js?

13 replies
Last updated: Jan 28, 2026
Hello Sanity, My .env.local file contains my project id and dataset name. I'm accessing them in my sanity configuration. However my NextJs application complains that I have to specify my projectId. If I hardcode the id to the sanity configuration, it works. What is actually going wrong here?
AI Update

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:

  1. Using SANITY_STUDIO_ prefix in a Next.js app (won't work - Next.js doesn't recognize this prefix)
  2. Forgetting the NEXT_PUBLIC_ prefix (variables won't be available in browser code)
  3. 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.

Show original thread
13 replies

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.

Was this answer helpful?