Unable to access Netlify environment variables when using Vite with react

How to access Netlify environment variable when using Vite with react ?

using import.meta.env.VITE_API_KEY but unable to get the netlify environment variable working?

when using .env.local file with VITE_API_KEY = 123 this is working. But when removing .env.local file and directly using VITE_API_KEY = 123 in netlify environment variables. It’s not working after build.

Please can anyone help with this issue ?

What site is this and how can we reproduce the issue?

Hey, thanks for the reply.

Just for test purpose created this site.
https://papaya-sprinkles-a2344b.netlify.app/

This is the site url. The expected result should 124. It’s NAN. As value is taken from netlify env variables.

In the above img when .env is commented out and the env values are taken directly from netlify it’s not working.

It appears you’re deploying manually. You need to deploy using Git for the environment variables from the UI to be injected in the code.

Hey, thank you this worked.

The updated site name is https://candid-kataifi-4ae3dd.netlify.app/

I have linked with the github repo. But I used netlify environment variables so that it is not shown on client side code. But after building when the app is deployed in site https://candid-kataifi-4ae3dd.netlify.app/

If I inspect the code then the import.meta.env.VITE_TEST_NUMBER value is visible from source tab. How to secure it? I knew from hosting if we set environment variables then that is secured.

That’s how client-side environment variables work.

Refer to: Env Variables and Modes | Vite

During production, these env variables are statically replaced .

To keep variables away from client-side code, you need to use them inside Netlify Functions.

Okay thanks for the update.
How to use this as mentioned in this article.

[Support Guide] How do I keep my API keys/tokens safe using Netlify Functions?.

I mean with $API_TOKEN as mentioned there.

That’s applicable if your client-side code doesn’t need it, for example:

if (process.env.NETLIFY === 'true') {
 // run something during build
} else {
  // run something else
}

It’s not possible to hide environment variables in client-side code. This is not a Netlify limitation. This is how browsers and JavaScript works.

Okay thank you for the details. Will try with functions.