Logo

dev-resources.site

for different kinds of informations.

Using environment variables in React and Vite

Published at
6/7/2024
Categories
webdev
react
vite
env
Author
harshalranjhani
Categories
4 categories in total
webdev
open
react
open
vite
open
env
open
Author
15 person written this
harshalranjhani
open
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! 🚀

env Article's
30 articles in total
Favicon
How to Use Environment Variables in a React.js App with Vite
Favicon
next-runtime-env usage in Documenso source code
Favicon
How to Build an Elm Land Project for Production
Favicon
การใช้ GitLab สำหรับแชร์ Configuration ให้คนในทีม โดยไม่ใช้แชท
Favicon
How to create a fullstack application using Django and Python Part 5
Favicon
Exploring DotenvX
Favicon
Setting up a React environment
Favicon
Using environment variables in React and Vite
Favicon
Exploring Node.js 20.6: Built-in Support for .env Files
Favicon
docker-compose will always load .env
Favicon
How to fix 'process' is not defined (React+Vite)
Favicon
Virtual Environments in Python Applications
Favicon
Decoding the Matrix: The Evolution of Environment Variables in Software
Favicon
Use Doppler instead of traditional .env files 🍕
Favicon
Além do básico: Uso de Variáveis de Ambiente em Aplicações Node e Nest
Favicon
Running scripts in Production
Favicon
Better DX for .env
Favicon
Navigating Environment Variables in Flutter Projects: Strategies for Effective Integration
Favicon
TIL - Today I Learn 12-11 18-11
Favicon
Generate a Random JWT Secret Key
Favicon
Next JS might be exposing your backend environment variables
Favicon
Environment variables and configuration anti patterns in Node.js applications
Favicon
Node(20.6.0) now supports built-in .env files
Favicon
How to keep your tokens secret?
Favicon
Criando um comando Artisan personalizado para definir valores de variáveis no .env no Laravel
Favicon
How to Effectively Remove .env File from Git Repo/History
Favicon
Vite environment variable's type casting/transforming
Favicon
Did you know docker-compose only takes environment variables from`.env` only?
Favicon
[HUGO]: How to use variables from .env
Favicon
Python – AWS Secrets Manager: Remote env vars

Featured ones: