🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

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
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

file at the project root level
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?