Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to Access Environment Variables in Sanity.json from Next.js

1 replies
Last updated: Apr 13, 2021
Hi, is there a clean way to access the environment variables in sanity.json from next.js? I'm going off of the Next.js blog tutorial: https://www.sanity.io/blog/build-your-own-blog-with-sanity-and-next-js and would like to configure the client to use environment variables in sanity.json.
The tutorial says to copy what's in sanity.json (below). But I'd like the deployed version in production to know to use the production data set. I'm outside of the studio dir and therefore am not running sanity start or sanity build. I'm deploying using Netlify


// client.js
import sanityClient from '@sanity/client'

export default sanityClient({
  projectId: 'your-project-id', // you can find this in sanity.json
  dataset: 'production', // or the name you chose in step 1
  useCdn: true // `false` if you want to ensure fresh data
})
Apr 13, 2021, 2:29 AM
your
client.js
file
import sanityClient from '@sanity/client'
const client = sanityClient({
        projectId: process.env.SANITY_PROJECT_ID,
        dataset: process.env.SANITY_DATASET,
        token: '', // or leave blank for unauthenticated usage
        useCdn: false, // `true` or `false` if you want to ensure fresh data
    })

.env.local
file at the project root level
SANITY_PROJECT_ID=here
SANITY_DATASET=here
no quotes
Next JS supports .env files

https://nextjs.org/docs/basic-features/environment-variables I hope that helps
Apr 13, 2021, 3:34 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?