I was setting up Sanity Studio for a project when I ran npx sanity dev and got hit with an error: "Missing environment variable: NEXT_PUBLIC_SANITY_DATASET". The frustrating part? The variable was clearly defined in my .env file. After digging into it, I realized the issue happens in two places. Here's exactly how to fix it.
The Root Cause
When you run npx sanity dev, the Sanity CLI doesn't automatically load your .env file like Next.js does. Additionally, client-side components that import from your env.ts file can't access environment variables the same way server-side code can. The browser can't read .env files directly.
Fix #1: Load dotenv in sanity.cli.ts
Your Sanity CLI configuration file needs to explicitly load environment variables. Open sanity.cli.ts and add the dotenv import at the top:
The import 'dotenv/config' line tells Node.js to load your .env file before anything else runs. This ensures the environment variables are available when the CLI initializes.
Fix #2: Use Fallback Values in env.ts
The second issue is in your src/lib/sanity/env.ts file. If client-side components import from this file and the environment variables aren't available in the browser context, you'll get an error. Instead of throwing an error with assertValue(), provide sensible defaults:
This way, if the environment variables are available (injected by Next.js at build time), they get used. If not, the fallback values keep your client-side components working without throwing errors.
Why Both Fixes Matter
The CLI fix ensures the Sanity CLI commands have access to your project configuration. The fallback values ensure that client-side code (like custom Sanity Studio components) doesn't crash when environment variables aren't directly accessible in the browser.
Now when you run npx sanity dev, it'll load your environment variables correctly, and your client-side components will work without errors.
Let me know in the comments if you hit any other environment variable issues with Sanity, and subscribe for more practical development guides.