DEV Community

Cover image for Using environment variables in React and Vite
Harshal Ranjhani for CodeParrot

Posted on • Originally published at 10xdev.codeparrot.ai

Using environment variables in React and Vite

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

  • Create a .env file in the root of your React project. You can create this file manually or use the touch command in your terminal.
touch .env
Enter fullscreen mode Exit fullscreen mode
  • Add your environment variables to the .env file. Prefix your variables with REACT_APP_ to make them available in your React application.
REACT_APP_API_KEY=your-api-key
REACT_APP_API_URL=https://api.example.com
Enter fullscreen mode Exit fullscreen mode
  • Access your environment variables in your React components using process.env.
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);
Enter fullscreen mode Exit fullscreen mode
  • Remember to restart your development server after adding or updating environment variables in your .env file.

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.

  • Create a .env file in the root of your Vite project. You can create this file manually or use the touch command in your terminal.
touch .env
Enter fullscreen mode Exit fullscreen mode
  • Add your environment variables to the .env file. Prefix your variables with VITE_ to make them available in your Vite application.
VITE_API_KEY=your-api-key
VITE_API_URL=https://api.example.com
Enter fullscreen mode Exit fullscreen mode
  • Access your environment variables in your Vite application using import.meta.env.
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);
Enter fullscreen mode Exit fullscreen mode
  • Remember to restart your development server after adding or updating environment variables in your .env file.

Benefits of using Vite for environment variables

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

  • .env: Loaded in all cases.
  • .env.local: Loaded in all cases, ignored by git.
  • .env.[mode]: Loaded only in the specified mode (e.g., .env.production).
  • .env.[mode].local: Loaded only in the specified mode, ignored by git.

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;
}
Enter fullscreen mode Exit fullscreen mode

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"]
}
Enter fullscreen mode Exit fullscreen mode

Note

  • Environment variables prefixed with REACT_APP_ are automatically embedded into the build by Create React App. You don't need to use a package like dotenv to load environment variables in your React application.

  • Vite automatically loads environment variables from .env files and makes them available in your application using import.meta.env. You don't need to use a package like dotenv to load environment variables in your Vite application.

  • Make sure to add your .env files to your .gitignore file to prevent them from being committed to your version control system.

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! 🚀

Top comments (3)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

It really isn't a great way to manage secrets or configuration settings. To start with, it is an archaic, flat key-value pair system dating from 40 or more years ago. To continue, the concept of environment variables doesn't apply to browser applications, so any efforts that have been made towards implementing it are hacky and require tooling. The dotenv package is for NodeJS applications.

Collapse
 
angelotheman profile image
Angel Oduro-Temeng Twumasi

Could you provide an alternative solution for this?

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

There is a very popular package called config that does hierarchical configuration, and of course there is also the package I created, wj-config, which in my opinion is more powerful than config + env together. It is just a matter of taste, though, as my package is modeled after .Net Configuration, and Javascripters tend to dislike it.

I must warn you, though, that I don't remember if config can be used in both NodeJS and the browser. Mine can be used equally in both.

I have had other priorities at hand, but FYI, I'll be re-writing wj-config because it was my first-ever TypeScript project. Its TypeScript is not good at all. I can do better now.