DEV Community

Cover image for How to use Environment Variables in Vite(React Template Example)

How to use Environment Variables in Vite(React Template Example)

RamaDevsign on August 27, 2021

tl:dr — Use import.meta.env instead of process.env Vite is a handy build tool when you want to spin up a quick react application. In this guide, ...
Collapse
 
chris13830450 profile image
Chris

Thank you very much for this, just migrated from using CRA to Vite and this issue had been bothering me.

Collapse
 
wendumaris profile image
Nwafor Stellamaris Chinwendu

Thanks for this. it really helps

Collapse
 
allexon profile image
Alexon da Silva Moreira

I achieved!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

I paste this in this file -> .env
VITE_OPS='ops_here'

having to take it like this in any component
import.meta.env.VITE_OPS

but still i have a doubt if i need
of an environment variable on the front but that
that it is not exposed to the user

Collapse
 
allexon profile image
Alexon da Silva Moreira

What torture in Vite, I'm trying to get the environment variable, when I run yarn dev

I paste this in this file -> vite-env.d.ts
OPS='ops_here'

having to take it like this in any component
import.meta.env.VITE_OPS

always give undefined

why do they invent so much....

Collapse
 
devshetty profile image
Deveesh Shetty

I had it in the root folder so it was not working... Moved the folder to src then it worked.

Collapse
 
frankoadeleye profile image
Frank Adeleye

Thanks for this!

!IMPORTANT:
Let's remember the prefix each variable we want exposed with the 'VITE_' phrase.
E.g, use VITE_BASE_URL instead of BASE_URL_OF_VITE unless it's something you don't want exposed.

Cheers

Collapse
 
yohannestz profile image
YohannesTz

hi, good read. also add a disclaimer this might cause a leak for api keys.

Collapse
 
marieshix1 profile image
Wanjiku Maina.

Thank you. This has worked

Collapse
 
jacetech profile image
Chidindu Emmanuel Aneke

Hi,
Does it also what in the index.html file?

Collapse
 
amphilip profile image
Philip Mac

I'm trying to use Sanity as my cms and import.meta.env is nt working. could it be because sanity uses webpack?

Collapse
 
ymodepalli profile image
Yaswanth

Thanks Bhai! Life Saver ❤

Collapse
 
annajaffar profile image
anna

Thank you so much, I was struggling while learning about using geolocation in JS in React. Kept on getting this error, even chatgpt couldnt help.