How to use Environment Variables in Vite(React Template Example)
Using environment variables when working with reactjs template inside Vite
tl:dr — Use
import.meta.env instead of
Vite is a handy build tool when you want to spin up a quick react application. In this guide, I will walk you through how to use environment variables inside a react application template created though vite.
This guide assumes that you know some basics of scaffolding a vite application template and also the workings of environment variables . A brief disclaimer, environment variables only store secrets during the development phase of your project. Secret or sensitive keys will be visible after a production build so be careful not to expose sensitive keys at build time.
Sometime back when doing a live code presentation, I wanted to use some keys from a database that was to initialize a connection to the database. The best approach would be to write all the keys inside a
process.env.REACT_APP_SOME_VALUE but in this instance, the react application stopped rendering information on the screen. The console error read "process is not defined". Even after installing the npm package dotenv, the error still persisted.
The solution is actually inside the official vite documentation. Instead of using
process.env.REACT_APP_SOME_VALUE which is common with other projects, inside vite we use
import.meta.env.SOME_VALUE. When you want to expose some info inside the frontend you will have to append the statement with VITE i.e.
import.meta.env.VITE_SOME_VALUE statement, we can now use environment variables inside a react application initialized inside of vite. Thank you for reading this brief writeup and hope this comes in handy when working with react inside vite.