Using .env file with Sanity client.js configuration

13 replies
Last updated: Jan 28, 2026
Hello Sanity world! I am currently building a site free of charge for a local non-profit here in Austin, TX. I used React(CRA) and Tailwinds for the front-end to deploy to Netlify. Love how simple Sanity CMS was to setup. Nice and straightforward for the client to update content as well! Are there any docs/examples available for using a .env file with the Sanity client.js file?
user Y
AI Update

That's awesome you're helping out a local non-profit in Austin! Great to hear Sanity is working well for you and your client. πŸŽ‰

For using environment variables with Create React App and the Sanity client, here's what you need to know:

Create React App Environment Variables

CRA requires all environment variables to be prefixed with REACT_APP_ to be accessible in your browser code. Create a .env file in your project root:

REACT_APP_SANITY_PROJECT_ID=your-project-id
REACT_APP_SANITY_DATASET=production

Setting Up Your Sanity Client

In your client.js (or wherever you initialize the Sanity client):

import { createClient } from '@sanity/client'

export const client = createClient({
  projectId: process.env.REACT_APP_SANITY_PROJECT_ID,
  dataset: process.env.REACT_APP_SANITY_DATASET,
  useCdn: true, // set to `false` to bypass the edge cache
  apiVersion: '2024-01-01', // use current date (YYYY-MM-DD) to target the latest API version
})

Important Notes:

  1. Public Values: Your project ID and dataset name aren't secret - they'll be exposed in your built application. This is totally normal and expected for client-side queries, as mentioned in the Sanity environment variables documentation.

  2. useCdn: Set this to true for production (faster reads). Only set to false if you need the absolute latest data or are using authenticated requests.

  3. Tokens: If you need to write data or access private datasets, you'd add a token, but never commit tokens to your .env file in version control. Add .env to your .gitignore.

For Netlify Deployment

You'll need to add these same environment variables in your Netlify dashboard under Site settings β†’ Environment variables. Use the same names (REACT_APP_SANITY_PROJECT_ID, etc.). Check out the Netlify environment variables docs for details.

Restart Your Dev Server

After creating or modifying your .env file, restart your CRA dev server for the changes to take effect.

The key difference from Sanity Studio (which uses the SANITY_STUDIO_ prefix) is that your React frontend needs the REACT_APP_ prefix for CRA to expose those variables to the browser. Happy building! πŸš€

Show original thread
13 replies

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?