I had to set some environment variables in the frontend of a dApp I’m working on, which uses TypeScript and Vite for module bundling. Initially, I created a .env
file and declared a variable inside it. But, attempting to access it in my code with process.env.NAME_OF_VARIABLE
did not work; the value was undefined
.
This approach failing, I tried setting the environment variable directly when starting the app. In my package.json
, I modified the start command as follows:
"start:ui": "cd ui && export NAME=Rabi && yarn dev",
This method also failed. And now I was confused. I went on to check Vite’s documentation and discovered that Vite encapsulates all environment variables within the import.meta.env
object. Also, for variables to be included in this object, they must be prefixed with VITE_
. I made this change:
"start:ui": "cd ui && export VITE_NAME=Rabi && yarn dev",
After prefixing my variable names accordingly, they became accessible in my code and I was able to use them.
It was interesting to learn that module bundlers like Vite inject the values of environment variables into the code at build time. Vite’s documentation offers a thorough explanation of how they handle environment variables, which you can read about here.