Why use .env files?
While building our web app, we might need to store sensitive information such as API keys, database passwords, and other variables that are required for the application to run. Now we wouldn't want such information to be hard-coded into our application code for everyone to see right? ๐ง In such cases, the .env file comes to the rescue!
How usage of .env files differ in the Vite+React app from create-react-app?
This is the traditional way CRA handles an environment variable.
Let's see how Vite+React app handles .env:
- Here, we have the default Vite+React app template.
- Now, create a
.env.local
file in our project's root directory.
We're using.local
as .local files are present in .gitignore by default. A normal .env file would work fine as well but it would get pushed into our git repository.
- Let's add some environment variables to our
.env
file.
Now, in the
App.jsx
file, render the contents of the environment variable.As you can see, Vite handles environment variables in a different manner than React. It uses the
import.meta.env
object to expose the environment variables.
Great! Let's go ahead and start our application.
Hold on...Why did the second environment variable not get rendered?
That's because for preventing accidental leaks, Vite exposes only those variables that are prefixed with VITE_
to the Vite-processed code.
Some key takeaways:
Vite uses dotenv module to load environment variables.
Environment variables need to be prefixed with
VITE_
.To load the environment variables use
import.meta.env.VITE_YOUR_VAR_NAME
Check out https://vitejs.dev/guide/env-and-mode.html#env-variables for more advanced use cases.