How to Add Environment Variables in Vite App with React using .env file | Tutorial by @howdevyou

Posted by

Environment Variables in VITE + REACT

Environment Variables in VITE + REACT | add .env file to Vite App

When working with Vite and React, it’s important to be able to handle environment variables in your application. Environment variables are a way to set configuration options for your app based on the environment it’s running in, such as development, staging, or production. This allows you to easily manage different settings for different environments without having to change your code.

In Vite, you can add environment variables to your application by creating a .env file in the root of your project. This file should contain key-value pairs of the variables you want to use. For example:

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

You can then access these environment variables in your React application using the process.env object. For example, to access the API URL:

const apiUrl = process.env.REACT_APP_API_URL;

This allows you to easily switch between different API URLs based on the environment your app is running in, without having to modify your code.

When using environment variables in your Vite + React application, it’s important to keep security in mind. Avoid storing sensitive information such as API keys directly in your .env file, and be careful about how you handle and store these variables in your code.

Overall, environment variables are a powerful tool for managing configuration in your Vite + React application. By adding a .env file to your Vite app, you can easily manage different settings for different environments, making it easier to develop and deploy your app.

Feel free to follow @howdevyou on social media for more development tips and tutorials!

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

thank you bro

@marcusdevsurfer
10 months ago

Good video, I tried importing dotenv from ''dotenv' but isn't working. After that I tried importing { loadEnv } from 'vite' and following the steps of this video and is working now.

@randre_98
10 months ago

This works for testing .env in development mode. Thank you !

@fatima_Ezahra
10 months ago

It is successful Thank you

@batuhanbahayetmez4452
10 months ago

it's not working

@faizanshaikh2351
10 months ago

so we have to define there each env variables