Home
Support Forums

Vite/React Environment Variables

So we just moved from CRA to Vite for our React app. In CRA we used the .env file to get the Netlify environment variables into React.

CRA .env file:

# get the Netlify environment variables
REACT_APP_COMMIT_REF=$COMMIT_REF
REACT_APP_PULL_REQUEST=$PULL_REQUEST
REACT_APP_REVIEW_ID=$REVIEW_ID

When we did this I could then access these variables in our React code with

process.env.REACT_APP_COMMIT_REF

.

Now I have moved to Vite and updated the .env file to:

# get the Netlify environment variables
VITE_COMMIT_REF=$COMMIT_REF
VITE_PULL_REQUEST=$PULL_REQUEST
VITE_REVIEW_ID=$REVIEW_ID

I try to use them with

import.meta.env.VITE_COMMIT_REF

but it’s undefined.

Does anyone know how to properly hook this up in a Vite/React app?

Could you try to set the variables in Netlify UI to make sure it’s not a problem of .env file being read/ignored?

Additionally, if that still doesn’t work, just to go to a primitive stage to debug, try setting a static value for the variables like VITE_COMMIT_REF=1 and see if you can get that value to work.

Yes that works. I have a VITE_ENVIRONMENT variable being set through the UI and it works fine. I want dynamic ones like commit ref or review id though so I need it to work through the .env file as well.

1 Like

Hi @mikecousins,

Could you provide us a repo to test this? A simple bare-bone setup should do too as long as it’s having the same problem.

Also, just to confirm, does this problem occur locally?

Repo: https://github.com/mikecousins/netlify-vite-environment

Deployed: https://vite-env-test.netlify.app/

Commit ref should be injected by Netlify into the .env file then should be displayed. It doesn’t work.
Netlify UI variable is injected by the Netlify UI straight into the app.
Not Netlify is a hardcoded variable in the .env file to prove the .env file is working.

I just checked and seems like your repo is private.

Oops, fixed that, sorry.

This took some time, but you can do it by changing your build command to VITE_COMMIT_REF=$COMMIT_REF npm run build. Then you won’t need to set the variable anywhere else. Example: https://compassionate-bassi-1f663e.netlify.app

So you can’t use the .env file like you can in Create React App?

Actually I’m kind of surprised that it worked in CRA as well. It was not supposed to. This would shed some light:

1 Like