Using .env files with Sanity client.js in React CRA app
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:
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.
useCdn: Set this to
truefor production (faster reads). Only set tofalseif you need the absolute latest data or are using authenticated requests.Tokens: If you need to write data or access private datasets, you'd add a token, but never commit tokens to your
.envfile in version control. Add.envto 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! π
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.