,

Using Environment Variables (.env) in a React JS App with VITE

Posted by

How to use environment variables in React app – VITE

How to use environment variables in React app – VITE

Environment variables are a convenient way to store sensitive information or configuration values in your React application. In this article, we will explore how to use environment variables in a React app using VITE.

Step 1: Install VITE

VITE is a build tool for modern web development that is used to build React applications. To get started with VITE, you can install it using npm:

npm install -g create-vite

Step 2: Create a .env file

In your React project root directory, create a .env file. This file will be used to store your environment variables. For example:


REACT_APP_API_URL=https://api.example.com
REACT_APP_SECRET_KEY=your-secret-key

Step 3: Access environment variables in your React components

You can access your environment variables in your React components by using process.env. For example:


const apiUrl = process.env.REACT_APP_API_URL;
const secretKey = process.env.REACT_APP_SECRET_KEY;

Step 4: Use environment variables during development

During development, you can use your environment variables in your VITE configuration. For example:


import { defineConfig } from 'vite';

export default defineConfig({
env: {
API_URL: process.env.REACT_APP_API_URL,
SECRET_KEY: process.env.REACT_APP_SECRET_KEY
}
});

Step 5: Use environment variables in your production build

When you build your React app for production, VITE will automatically replace your environment variables with their actual values. This means that you can safely use your environment variables in your production build without exposing sensitive information.

Conclusion

Using environment variables in your React app with VITE is a powerful and convenient way to manage your configuration values. By following the steps outlined in this article, you can easily use environment variables in your React app while keeping your sensitive information secure.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@abasionoikangenyin5383
6 months ago

Thanks a lot this saved my 5hrs stress of finding how to make my .env api show up in the webpage

@saltygamer8435
6 months ago

Helped out a lot

@kingheisenberg674
6 months ago

thanks buddy , this helped a lot . was searching for the correct way for a long time