👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Issue with process.env variables causing configuration error in Sanity client setup.

10 replies
Last updated: Apr 22, 2022
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?
Apr 20, 2022, 6:17 PM
Hardcoded, it has all the vars fine. From process.env, it doesn't even get that far. It errors on initConfig

index.js?46cb:369 Uncaught Error: Configuration must contain `projectId`
    at exports.initConfig (config.js?2e28:42:1)
Apr 20, 2022, 6:23 PM
I also tried pulling out those vars into consts using destructuring on process.env above
options
and got an error saying process is undefined. This is running dev, not build + production
Apr 20, 2022, 6:27 PM
Got it. Since you said it had been working previously, did you change anything about your env file?
Apr 20, 2022, 6:28 PM
.env and the sanity client init file were unchanged. The biggest change related was moving the usage from getStaticProps (next.js) to useEffect
Apr 20, 2022, 6:30 PM
The fact that process was undefined with the destructuring approach leads me to believe it's probably not a sanity issue, but I thought maybe someone else here might have had the same problem.
Apr 20, 2022, 6:31 PM
It does seem like it isn't a Sanity issue, but there have been a ton of questions around how to use env vars lately. Definitely still helpful to debug here! Are you able to share your repo so I can take a look? You can send me a zip of it over DM if you don't want it to be public.
Also sidenote, it's not necessary to obscure your dataset name and project id. Those will be publicly visible when you perform a query. They're not considered secret in the same way an API token it.
Apr 20, 2022, 6:34 PM
Sorry, not allowed to share the repo or codebase. I appreciate the offer to help though! I'll try to figure it out with my teammates.
Apr 20, 2022, 6:37 PM
user M
I figured out the problem and thought I'd let you know in case someone else runs into it. It was an issue with env vars in next.js as explained here: https://nextjs.org/docs/api-reference/next.config.js/environment-variables
Apr 22, 2022, 1:41 PM
Thanks for the update Jim! Really appreciate it!
Apr 22, 2022, 4:54 PM

Sanity– build remarkable experiences at scale

Sanity is a modern 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?