Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How To Configure And Use Environment Variables in NestJS?
Next article icon

How Can I Use Vite Env Variables in vite.config.js?

Last Updated : 09 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Vite is a fast and modern front-end build tool that provides an efficient way to develop web applications. One of its powerful features is the ability to use environment variables, which can help you customize your app's behaviour based on different environments.

This guide will walk you through how to use Vite environment variables (.env files) within your vite.config.js file, allowing you to configure Vite dynamically based on these settings.

Understanding Environment Variables in Vite

Vite supports environment variables that can be defined in .env files. By default, Vite will load environment variables from:

  • .env Loaded in all cases.
  • .env.local: Loaded in all cases, ignored by Git.
  • .env.development: Only loaded in development mode.
  • .env.production: Only loaded in production mode.

Environment variables that need to be exposed to the Vite application must be prefixed with VITE_. These variables are then accessible in the application via import.meta.env.

Why Use Environment Variables in vite.config.js?

Using environment variables in vite.config.js can help you:

  • Configure plugins: Adjust plugin settings based on environment variables.
  • Set build options: Change build configurations like output paths, minification, or base URLs.
  • Control server settings: Adjust development server settings like port numbers or proxies.

Steps To Use Environment Variables in vite.config.js

Step 1: Set Up the Vite Project with React

Initialize a New Vite Project

npm create vite@latest vite-env-variables-react -- --template react
cd vite-env-variables-react
npm install dotenv

Step 2: Define Environment Variables

Create a .env File At the root of your project, create a .env file and define your environment variables. Remember to prefix variables with VITE_ to make them available in your Vite configuration and application code.

VITE_API_URL=https://api.example.com
VITE_API_KEY=123456789
VITE_PORT=4000
VITE_USE_LEGACY=true

Step 3: Configure Vite to Use Environment Variables

Edit vite.config.js: In your vite.config.js file, use the dotenv package to load environment variables and configure Vite accordingly.

JavaScript
//vite.config.js  import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import legacy from '@vitejs/plugin-legacy';  import dotenv from 'dotenv'; dotenv.config();  const apiUrl = process.env.VITE_API_URL; const apiKey = process.env.VITE_API_KEY; const useLegacy = process.env.VITE_USE_LEGACY === 'true'; const port = parseInt(process.env.VITE_PORT, 10) || 3000;  export default defineConfig({     plugins: [         react(),         useLegacy && legacy({             targets: ['defaults', 'not IE 11']         }),     ].filter(Boolean),     define: {         __API_URL__: JSON.stringify(apiUrl),         __API_KEY__: JSON.stringify(apiKey),     },     server: {         port: port,         proxy: {             '/api': {                 target: apiUrl,                 changeOrigin: true,                 secure: false,             },         },     },     build: {         sourcemap: process.env.VITE_SOURCEMAP === 'true',         outDir: process.env.VITE_OUTPUT_DIR || 'dist',     }, }); 

Step 4: Access Environment Variables in Your React Application

You can use environment variables directly in your React application code via import.meta.env.

JavaScript
//src/main.jsx  import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import './index.css';  console.log('API URL:', import.meta.env.VITE_API_URL);  ReactDOM.createRoot(document.getElementById('root')).render(     <React.StrictMode>         <App />     </React.StrictMode> ); 
JavaScript
//src/App.jsx  import React from 'react';  function App() {     return (         <div>             <h1>Vite Environment Variables Example</h1>             <p>API URL: {import.meta.env.VITE_API_URL}</p>             <p>API Key: {import.meta.env.VITE_API_KEY}</p>         </div>     ); }  export default App; 

Step 5: Update Your package.json with Scripts

Add scripts for starting the development server and building the project

{
"name": "vite-env-variables-react",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview",
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
},
"dependencies": {
"@vitejs/plugin-legacy": "^5.4.2",
"dotenv": "^16.4.5",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"eslint": "^9.9.0",
"eslint-plugin-react": "^7.35.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"vite": "^5.4.1"
}
}

To start the application run the following command.

npm run dev

Output

cew
How Can I Use Vite Env Variables in vite.config.js

Common Use Cases

1. Configuring Plugins with Environment Variables

Environment variables can be used to enable or disable plugins or configure them conditionally:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import legacy from '@vitejs/plugin-legacy';

// Load environment variables
import dotenv from 'dotenv';
dotenv.config();

const useLegacy = process.env.VITE_USE_LEGACY === 'true';

export default defineConfig({
plugins: [
vue(),
useLegacy && legacy({
targets: ['defaults', 'not IE 11']
}),
].filter(Boolean),
});

2. Dynamic Base URL for Assets

If you need to set a dynamic base URL for your assets based on environment:

export default defineConfig({
base: process.env.VITE_ASSET_BASE_URL || '/',
});

3. Environment-Based Server Configuration

Configure the Vite development server with environment-specific settings:

export default defineConfig({
server: {
host: process.env.VITE_SERVER_HOST || 'localhost',
port: parseInt(process.env.VITE_SERVER_PORT, 10) || 3000,
open: process.env.VITE_SERVER_OPEN === 'true',
},
});

Best Practices

  1. Keep Secrets Secure: Avoid putting sensitive data (like API keys) directly in .env files, as these files might be exposed. For sensitive data, consider using server-side environment management solutions.
  2. Use Consistent Naming Conventions: Prefix all environment variables with VITE_ to avoid conflicts and make it clear which variables are intended for the client-side.
  3. Type Coercion: Be mindful of type coercion when using environment variables. Use JSON.stringify() for strings or parse values if needed.
  4. Check for Availability: Always provide default values when accessing environment variables in vite.config.js to ensure your application doesn't break if a variable is missing.

Next Article
How To Configure And Use Environment Variables in NestJS?

S

swati4934
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • vite

Similar Reads

  • How to Use Environment Variables in Vite?
    In order to create your Vite application in different environments such as development, staging and production, you need to use environment variables. They enable you to manage confidential data like API keys or service URLs without having to code them inside your source code. By using environment v
    3 min read
  • How To Configure And Use Environment Variables in NestJS?
    Environment variables are an important part of application development, allowing developers to configure applications in different environments (development, staging, production) without hardcoding sensitive or environment-specific information into the application code. In this article, we'll walk t
    2 min read
  • How to save connection result in a variable in Node.js ?
    We are going to use the query function in MySQL library in node.js that will return our output as expected. Using this approach, we can save connection result in a variable in Node.js. Setting up environment and Execution: Step 1: Initialize node project using the following command. npm init Step 2:
    1 min read
  • How to set or get the config variables in Codeigniter ?
    Config Class: The Config class provides means to retrieve configuration preferences. The config items in Codeigniter can be set and get in the environment. The config value $this->config can be used to get and set items in the environment. The config items are contained within an array, namely, $
    2 min read
  • How To Set Custom Vite Config Settings In Angular 17?
    Vite is a powerful tool that enhances the development experience for web applications, especially large and complex applications. Angular doesn’t use Vite by default; it uses the Angular CLI and Webpack for build tooling. However, you can configure Angular to use Vite instead of Webpack with a bit o
    2 min read
  • NODE_ENV Variables and How to Use Them ?
    Introduction: NODE_ENV variables are environment variables that are made popularized by the express framework. The value of this type of variable can be set dynamically depending on the environment(i.e., development/production) the program is running on. The NODE_ENV works like a flag which indicate
    2 min read
  • How to Configure multiple View Engines in Express.js ?
    View engines present in web application framework are basically the template engines that allow us to embed dynamic content into the web pages, render them on the server, and send them to the client. With the help of these, we can serve dynamic data, and utilise the template inheritance properties t
    3 min read
  • How to Load environment variables from .env file using Vite?
    The environment variables in the application are managed through .env files in a Vite project, allowing you to configure and access various settings dynamically. By prefixing variables with VITE_, Vite exposes them to your application’s runtime environment. This approach facilitates different config
    2 min read
  • How to Configure Proxy in Vite?
    Vite is a popular build tool for modern web libraries and frameworks like React and Vue. It provides features such as dependency resolving, pre-bundling, hot module replacement, typescript support. Using vite you can configure a proxy to handle requests to different backends or APIs during developme
    3 min read
  • How to Initialize Firebase in Vite and VueJS?
    Firebase with Vite and Vue Firebase, combined with Vite and Vue, opens up a powerful combination of real-time capability, fast development, and seamless backend integration. Firebase offers a real-time database, authentication, and cloud storage services that vastly reduce having to manage any backe
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences