😎 Discover cool tips and tricks for customization in our next Developer Deep Dive virtual event - sign up now!

Trouble with environment variables in a Next.js project

5 replies
Last updated: May 28, 2023
can someone please help me with this:I do have a .env.local with the correct name and value for the env variable. I know this because I used those same values to get access to my content in my local site. So, why did this not work. Thank you in advance.
This is a nextjs project (if that helps at all)
May 27, 2023, 10:29 PM
When you start your local dev environment, does it say that it picks up the env.local file in your console?
May 28, 2023, 6:44 AM
Yes, it does. When I go to /studio locally everything works as expected. I ended up removing the assert function used in sanity.cli.ts file (or the other one in the root) and did sth like:
export const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET || 'production'
And that worked for now but I don't think that's a good idea. But for now, doing that helped.
May 28, 2023, 6:57 AM
I even printed out the env variables in the same file and it.printed correctly. Somehow that assert function call kept throwing Error. I couldn't solve it so had to go that route
May 28, 2023, 6:58 AM
Hmm are you trying to pick them up in your front end or in your studio? Seems like you’re inside a studio when I look at the url? I think env variables inside the studio requires a bit more work/setup: https://www.sanity.io/docs/environment-variables
May 28, 2023, 7:33 AM
I got that error after I ran
sanity build
and then
sanity deploy
and tried to visit the URL. After reading the docs, I think I used the NEXT_PUBLIC_ variables for both local studio and the version I was trying to deploy. The doc says it should start with SANITY_STUDIO_ . Thank you for your time. I will resolve it now.
May 28, 2023, 1:12 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?