How to Use Environment Variables in Vite (React Template Example) and in CRA (Create React App)

Nishit BariyaNishit Bariya
3 min read

In this article, I am talking about how we can hide our sensitive information through .env

When developing React applications, it's often necessary to manage environment-specific configurations such as API endpoints, API keys, or other sensitive information. Properly managing these configurations is essential for maintaining a secure and flexible codebase. In this article, we will delve into how to effectively utilize .env files in both Create React App (CRA) and Vite-powered React applications. We'll also highlight the differences in handling environment variables between the two and address the common "process is not defined" error that can occur in Vite React apps.

Create React App (CRA)

What is a .env File?

A .env file is a plain text file that stores key-value pairs, typically used to hold configuration data. In the context of a CRA project, you can create environment-specific .env files like .env.development and .env.production. CRA automatically selects the appropriate .env file based on the current environment.

Steps to Use .env Files in CRA:

  1. Create a .env File: Begin by creating a .env file in the root directory of your CRA project. For instance:

     REACT_APP_API_KEY=your_api_key_here
     REACT_APP_API_ENDPOINT=https://api.example.com
    
  2. Accessing Environment Variables: To access these variables in your JavaScript code, prefix them with REACT_APP_. For example:

     const apiKey = process.env.REACT_APP_API_KEY;
     const apiUrl = process.env.REACT_APP_API_ENDPOINT;
    
  3. Usage in the Application: You can now freely use apiKey and apiUrl within your application code.

CRA automates the process of loading environment variables, eliminating the need for additional configuration.

Vite React App

What is Vite?

Vite is a build tool that prioritizes speed and efficiency. Unlike CRA, Vite does not rely on Webpack and offers a more streamlined development experience.

Using .env Files in Vite React Apps:

Vite takes a different approach to handling environment variables compared to CRA. Instead of automatically detecting environment-specific files, Vite necessitates manual configuration.

Steps to Use .env Files in Vite React Apps:

  1. Install the dotenv Package: Initially, install the dotenv package:

     npm install dotenv --save
    
  2. Create a .env File: Similarly to CRA, create a .env file in the root directory of your Vite React project:

     VITE_API_KEY=your_api_key_here
     VITE_API_ENDPOINT=https://api.example.com
    
  3. Configure Vite: Within your vite.config.js file, import and configure the dotenv package to load your .env file:

     import { defineConfig } from 'vite';
     import react from '@vitejs/plugin-react';
     import dotenv from 'dotenv';
    
     // Load environment variables from .env
     dotenv.config();
    
     export default defineConfig({
       plugins: [react()],
     });
    
  4. Accessing Environment Variables: You can directly access the variables in your code as follows:

     const apiKey = import.meta.env.VITE_API_KEY;
     const apiUrl = import.meta.env.VITE_API_ENDPOINT;
    

You can now use apiKey and apiUrl within your Vite React application.

Handling the "process is not defined" Error in Vite React Apps

A common issue encountered in Vite React apps is the "process is not defined" error. This error arises because Vite does not provide a global process object as Webpack does. To resolve this issue, you can employ the @rollup/plugin-replace plugin to create a fallback for process.env in your Vite application.

  1. Install the Plugin:

     npm install --save-dev @rollup/plugin-replace
    
  2. Configure the Plugin in Your vite.config.js File:

     import { defineConfig } from 'vite';
     import react from '@vitejs/plugin-react';
     import dotenv from 'dotenv';
     import replace from '@rollup/plugin-replace';
    
     dotenv.config();
    
     export default defineConfig({
       plugins: [
         react(),
         replace({
           'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
         }),
       ],
     });
    

By incorporating the @rollup/plugin-replace plugin, you ensure that your Vite React application can access process.env variables without encountering errors.

In summary, both Create React App and Vite React applications support the use of .env files for managing environment-specific configurations. However, they differ in their configuration and handling of environment variables. Understanding these distinctions and addressing common issues like the "process is not defined" error will facilitate efficient management of environment variables in your React projects.

11
Subscribe to my newsletter

Read articles from Nishit Bariya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nishit Bariya
Nishit Bariya

Postman Student Leader | Open-Source Advocate | ๐Ÿšฉ Vice-lead at @gdsckpgu |๐Ÿ‘จโ€๐Ÿ’ป Full Stack Developer | ๐Ÿ† 4x Hackathon Winner |