Sanity client not reading projectId from process.env - returns undefined

10 replies
Last updated: Nov 29, 2025
Hi All, up until this morning, my Sanity client config was working properly reading from .env and now it isn't. I have this as the client setup:
import sanityClient from "@sanity/client"

const options = {
  dataset: process.env.SANITY_DATASET_NAME,
  projectId: process.env.SANITY_PROJECT_ID,
  useCdn: process.env.NODE_ENV === "production",
}

export default sanityClient(options)
Now it's throwing `Uncaught Error: Configuration must contain `projectId``

If I hardcode the dataset name and project ID in the options object, it works fine.

Anyone else running into this?
AI Update

This is almost certainly an environment variable loading issue rather than a Sanity-specific problem. Since hardcoding works but process.env values don't, your environment variables aren't being loaded at runtime.

Here are the most common causes and solutions:

1. Client-side vs Server-side code

If this code is running in the browser (client-side), process.env won't automatically include your .env file variables. Most frameworks require special prefixes:

  • Next.js: Use NEXT_PUBLIC_ prefix for client-side variables:

    NEXT_PUBLIC_SANITY_PROJECT_ID=your-project-id
    NEXT_PUBLIC_SANITY_DATASET_NAME=production

    Then access with process.env.NEXT_PUBLIC_SANITY_PROJECT_ID

  • Vite/Svelte: Use VITE_ prefix and access via import.meta.env.VITE_SANITY_PROJECT_ID

  • Create React App: Use REACT_APP_ prefix

2. Server restart needed

If you just added/changed .env variables, you need to completely stop and restart your dev server. Hot reload doesn't pick up environment variable changes.

3. Wrong .env file location

Make sure your .env file is in the project root (same directory as package.json), not in a subdirectory.

4. .env file not being loaded

Some setups require dotenv to be configured. Add this at the very top of your entry file:

require('dotenv').config()

Quick debugging step:

Add this temporarily to see what's actually available:

console.log('Project ID:', process.env.SANITY_PROJECT_ID)
console.log('Dataset:', process.env.SANITY_DATASET_NAME)

If these log as undefined, your environment variables definitely aren't loading. The "worked this morning" aspect suggests either a dev server that needs restarting, or you recently moved this code from server-side to client-side rendering.

Show original thread
10 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?