Get started with  .env in your Vite+React App

Get started with .env in your Vite+React App

ยท

2 min read

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:

ย