Error deploying Sanity Studio with NextJS and Sanity, issue with environment variables

10 replies
Last updated: Jan 13, 2023
Hi everyone, I am currently working on this blog site using NextJS and Sanity.For some reason, in development everything works fine, but once I try to deploy sanity studio, I'm getting this error on sanity.cli.js file. Here are some screenshots with relevant files, but also you can check out the entire project here:
Jan 4, 2023, 4:00 PM
user K
! Where are you trying to deploy? If it's Vercel, it's likely not picking up on your environment variables. Did you add them when you were creating the deployment?
Jan 4, 2023, 5:05 PM
As you may notice on screenshot, I just tried to deploy the sanity studio itself. Later on, I planned to deploy the frontend side on Vercel.
Jan 4, 2023, 5:39 PM
Sorry, screenshots are really difficult to read so I wasn't able to see that you're using
sanity deploy
. Again, your environment variables are likely not being picked up.
Jan 4, 2023, 5:52 PM
Yeah, its strange, the sanity.config.js file is picking up the variables, while sanity.cli.js won't.I even tried to write projectId directly on sanity.cli file, and its the same issue as with env variables.
Jan 4, 2023, 5:56 PM
Can you try installing the dot env package and configuring it in your
? Since that config is used server-side it's not able to pick up your envs in the same way as the Studio config.
Jan 4, 2023, 5:59 PM
Unfortunately I get the exact same error, still sanity.cli doesn't pick up the variables. I'll try tomorrow to remove the studio from this project and reinitiate new one.Nevertheless, thank you for trying to help me, I'll update this tread if I manage to fix this issue.
Jan 4, 2023, 6:24 PM
Ah, bummer. Sorry to hear it didn't help. I'll also take a look at your repo to see if it's something else.
Jan 4, 2023, 6:25 PM
As promised, I found the way how to fix this error.I installed @next/env package in order to pick up the env variables while loading from server.
Hope this would help others with similar errors in their projects.
Jan 5, 2023, 5:28 PM
Thanks for sharing your solution!
Jan 5, 2023, 5:30 PM
This was the first thing that worked for me with env variables in the cli.Here to copy & paste:

import {loadEnvConfig} from '@next/env'
import {defineCliConfig} from 'sanity/cli'

const dev = process.env.NODE_ENV !== 'production'
loadEnvConfig(__dirname, dev, {info: () => null, error: console.error})

export default defineCliConfig({
  api: {
    projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
    dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
Jan 13, 2023, 1:25 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?