Environment variables undefined in sanity.cli.ts during deployment
Thanks for reporting this! I need to clarify something important about how environment variables work in Sanity Studio, because there's actually a misunderstanding here.
According to the official Sanity documentation on environment variables, environment variables prefixed with SANITY_STUDIO_ are automatically picked up by the Sanity CLI tool, development server and bundler. The docs explicitly state these variables are "available as process.env.SANITY_STUDIO_VARIABLE_NAME" in all CLI contexts.
This means your environment variables should work in sanity.cli.ts without needing dotenv.config(). If they're returning undefined during deployment, it's not a bug—it indicates your environment isn't properly configured.
Here's what's likely happening:
Sanity automatically loads .env files based on the active mode:
.env.developmentis loaded duringsanity start.env.productionis loaded duringsanity buildandsanity deploy.env(no suffix) is loaded in all cases
The solution:
- Create a
.env.productionfile in your project root:
SANITY_STUDIO_API_PROJECT_ID=your-project-id SANITY_STUDIO_API_DATASET=your-dataset
Or use
.env(without a suffix) if you want the same values in all environmentsYour
sanity.cli.tsshould work as-is:
import { defineCliConfig } from 'sanity/cli'
const projectId = process.env.SANITY_STUDIO_API_PROJECT_ID
const dataset = process.env.SANITY_STUDIO_API_DATASET
export default defineCliConfig({ api: { projectId, dataset } })Why your dotenv.config() workaround works:
You're manually loading environment variables before Sanity's automatic loading happens. This works, but it's treating the symptom rather than the root cause. The real issue is that your .env.production file is either missing or not in the right location.
Important note about the VITE_ prefix:
While VITE_ prefixed variables work (since Studio v3 uses Vite), the Sanity docs recommend using process.env over import.meta.env and sticking with the SANITY_STUDIO_ prefix. This keeps your code consistent across different contexts and makes future migrations easier.
If you're deploying via CI/CD:
Make sure your deployment environment either includes the .env.production file or sets the environment variables directly in your CI/CD configuration (like GitHub Actions secrets, Vercel environment variables, etc.).
The behavior you're experiencing isn't a bug—it's how environment variable loading is designed to work with different modes. The SANITY_STUDIO_ prefix should work everywhere the CLI runs, as long as your .env files are properly set up for each environment.
Show original thread11 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.