DEV Community

Afikode Olusola Emma
Afikode Olusola Emma

Posted on

SETTING UP ENVIRONMENT VARIABLES IN REACT-VITE PROJECTS

INTRODUCTION
It is no news that pushing some certain sensitive part of your code to a remote repository is not advisable for security reasons. Exposing things like base url, API keys etc makes your application very vulnerable to attacks. It is therefore imperative that sensitive parts of your codes are saved as environmental variables. This article will take you through keeping some sensitive part of your code when using Vite to set up your reactjs application.

SETTING UP ENV VARIABLES
To start with, there are quite a number of ways to set up react projects. Using Vite is one of the fastest ways of doing this. Vite helps to set up only necessary files, without adding some unnecessary loads on the setup itself. This article does not focus on Vite, rather it focuses on how to set up environment variables when working with a react project set up with Vite.

To set up a react project application with Vite, type in the terminal:

Image description

This command will give some subsequent actions (these actions are based on technology preference). It is very easy to follow, and you are not likely to have glitches.

Now, to set up your environment variable, create a file with the name .env (dot env) in your home directory (the same directory with your src folder). In your .env file, create a variable in the like below:

Image description

NOTE: Ensure that you start your variable name with VITE_, as only variables with such naming convention will be exposed to the naming convention.

The next process is how to make use of the variables in the respective files or components where they will be needed. To access the URL and KEY named above, type the following the components where you will be needing them:

Image description

You then have access to these variables and use them for whatever you intend in the respective components.

Conclusion
Following this pattern ensures that your env variables do not accidentally leak and get into hands that you do not want. I hope this article has been able to help you have a better understanding of setting up environment variables in vite-react applications.

Top comments (2)

Collapse
 
johnywhyte profile image
johnywhyte

An interesting, but theres a package called dotenv. I am guessing they serve the same purpose. why use vite over dotenv. I have on used dotenv on Node.js projects though. is VITE the best environment variable package for react apps? and why?

Collapse
 
junojulius profile image
Juno Burger

Vite is a build tool, akin to webpack.
It takes away quite a bit of setting up and boilerplate that you'd get with webpack and its dependencies, and is relatively fast (especially in combination with SWC).

It also has built-in support for environment variables.
dotenv is useful for a standalone package, since nodejs doesn't support handling environment variables out-of-the-box.