Trouble with environment variables in a Next.js project
I understand your frustration! Environment variable issues in Next.js projects with Sanity can be tricky. Here are the most common reasons why your .env.local file might not be working, even though the values are correct:
1. Variable Naming for Browser vs Server
In Next.js, where you use the environment variable matters:
- Server-side code (API routes,
getServerSideProps,getStaticProps): Can access variables without any prefix - Browser/client-side code: Requires the
NEXT_PUBLIC_prefix
If you're trying to use Sanity client in a component that runs in the browser, your variables need to look like this:
NEXT_PUBLIC_SANITY_PROJECT_ID=your-project-id NEXT_PUBLIC_SANITY_DATASET=production
Without the NEXT_PUBLIC_ prefix, Next.js won't expose them to the browser, even though they work fine in server-side code. This is the most common issue!
2. Server Restart Required
Did you restart your Next.js dev server after creating or modifying .env.local? Changes to environment variables require a full restart:
# Stop your dev server (Ctrl+C) and restart
npm run devHot reload doesn't pick up environment variable changes.
3. File Location
Make sure .env.local is in the root of your Next.js project (same directory as package.json and next.config.js), not in a subdirectory.
4. Sanity Studio vs Next.js App
If you have Sanity Studio embedded in your Next.js project, remember:
- Sanity Studio requires
SANITY_STUDIO_prefix for its own configuration - Next.js app requires
NEXT_PUBLIC_prefix for client-side code
You might need both:
# For Next.js client components NEXT_PUBLIC_SANITY_PROJECT_ID=your-project-id NEXT_PUBLIC_SANITY_DATASET=production # For embedded Sanity Studio SANITY_STUDIO_API_PROJECT_ID=your-project-id SANITY_STUDIO_API_DATASET=production
5. Vercel/Deployment Environment
If this is happening on Vercel or another host (not locally), you need to add the environment variables in your hosting platform's dashboard. The .env.local file is gitignored and won't be deployed.
Quick Debug
Add this to a component to see what's actually available:
console.log('Project ID:', process.env.NEXT_PUBLIC_SANITY_PROJECT_ID)
console.log('All public vars:', Object.keys(process.env).filter(k => k.startsWith('NEXT_PUBLIC_')))Based on the Sanity environment variables documentation, the prefix requirements are critical for proper configuration. The most likely culprit is missing the NEXT_PUBLIC_ prefix if you're using these variables in client-side React components.
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.