Using environment variables in React and Vite

June 7, 2024 (5mo ago)

Environment variables are a powerful way to manage secrets and configuration settings in your applications. They allow you to store sensitive information like API keys, database credentials, and other configuration settings outside of your codebase. This makes it easier to manage your application's configuration and reduces the risk of exposing sensitive information in your code.

This becomes highly useful when you are planning to make your code open-source or share it with others. In this article, we will learn how to use environment variables in React and Vite to manage secrets and configuration settings in your applications.

Using environment variables in React

touch .env
REACT_APP_API_KEY=your-api-key
REACT_APP_API_URL=https://api.example.com
const apiKey = process.env.REACT_APP_API_KEY;
const apiUrl = process.env.REACT_APP_API_URL;
 
console.log("API Key:", apiKey);
console.log("API URL:", apiUrl);

Using environment variables in Vite

Vite provides built-in support for environment variables using the .env files. You can create different .env files for different environments like development, production, and testing.

touch .env
VITE_API_KEY=your-api-key
VITE_API_URL=https://api.example.com
const apiKey = import.meta.env.VITE_API_KEY;
const apiUrl = import.meta.env.VITE_API_URL;
 
console.log("API Key:", apiKey);
console.log("API URL:", apiUrl);

Benefits of using Vite for environment variables

Vite uses .env files to load environment variables. You can create different .env files for different environments:

TypeScript Support

For TypeScript projects, you can enhance IntelliSense by defining custom environment variables. Create a vite-env.d.ts file in your src directory:

/// <reference types="vite/client" />
 
interface ImportMetaEnv {
  readonly VITE_APP_TITLE: string;
  // more env variables...
}
 
interface ImportMeta {
  readonly env: ImportMetaEnv;
}

If your code relies on types from browser environments such as DOM and WebWorker, you can update the lib field in tsconfig.json.

{
  "lib": ["WebWorker"]
}

Note

Using environment variables in React and Vite is a great way to manage secrets and configuration settings in your applications. It allows you to store sensitive information outside of your codebase and makes it easier to manage your application's configuration. I hope this article helps you understand how to use environment variables in React and Vite. Happy coding! 🚀