Using .env files with Sanity client.js in React CRA app

13 replies
Last updated: Jun 21, 2021
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! πŸš€

In the frontend
Thanks for the speedy response!
I'll confess to not being super knowledgeable with CRA, but in general, you should be able to specify a set of variables in your
.env
file in the root of your CRA app and then you can use them with
process.env.REACT_APP_MY_VARIABLE
.
I think CRA will handle the rest for you.

It's important to note that you don't want to put sensitive env variables into CRA, since they'll be in your bundle. Your Sanity project ID and dataset are ok (since they're public anyway), but don't put write token in those env variables.

CRA's docs on env variables are handy for this:
https://create-react-app.dev/docs/adding-custom-environment-variables/ (other frontends may not have automatic import of .env files and you may need something like
dotenv
npm package, but CRA, Nextjs and others do some of the magic for you)
I found these docs https://www.sanity.io/docs/studio-environment-variables But I'm still getting an error when starting my project locally
Those docs are how you'd use Env variables to make the Studio work. We don't have too much in the way of documentation around using env variables in your frontend, since that's dependent on the framework (each framework handles it differently)
CRA I think wants all of your env variables to start with
REACT_APP_
So
REACT_APP_SANITY_PROJECT_ID = 'dkei24k'
or something similar
Ok I will attempt that again and see what I get. Thank you for all the info!
No problem! Sorry for lack of a definitive path for you. If those docs don't work for you, post your client.js and any code that's using the variables and we can try to troubleshoot. I'll be in meetings most of the rest of today, but i'll let some others know to check in πŸ˜„
Hey Brian,
So I'm still having issues with getting connected to my Sanity Studio with using an .env file. When I have the projectID manually typed then I have no errors and all content is loaded. When I try to use the .env path the error I receive is
I'm using Netlify to deploy the site. I've include these variables into my Environment Variables inside Netlify for Deployment.
My question is will anyone have access to the Sanity CMS if the projectID is visible within the codebase? Even without an invitation to read and/or edit the Sanity Studio for this project?

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?