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 Load environment variables from .env file using Vite?
Next article icon

How to Use Environment Variables in Vite?

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 variables, it is easy to change configurations depending on the environment in which the application runs; making sure that they would encounter no errors or security problems. This article will help you understand how to set up and use environment variables with Vite, including some common use cases and best practices.

These are the following approaches:

Table of Content

  • Using '.env' Files
  • Directly in the Vite Configuration FIle
  • Accessing Environment Variables in your Code

Steps to Create Vite Application

Step 1: Ensure NodeJs is installed in your machine, if not download it from the official website.

Step 2: Create a new Vite Project by using the following command:

npm create vite@latest vite-project --template

Step 3: Select the framework, choose React using the downward arrow key.

Vanilla
Vue
React
Preact
Lit
Svelte
Solid
Qwik
Others

Step 4: Select Variant, choose any one of the below variants of your choice by using the downward arrow key, here we choose JavaScript variant.

TypeScript
TypeScript + SWC
JavaScript
JavaScript + SWC

Step 5: Now, switch to vite-project directory

cd vite-project

Step 6: Install Dependencies

npm install

Package.json:

"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.2.0"
}

Project Structure:

Screenshot_20240805_203932
Project structure


Step 7: Start the server by using the following command

npm run dev

Now, the Vite app is running on your local host.

 ➜  Local:   http://localhost:5173/

Approach 1: Using '.env' Files

  • Vite allows loading of environment variables from .env files. These are files which contain values that you want to be available everywhere in the application.
  • Make a file named .env at project root and then define variables in following syntax: VITE_SOME_KEY = some_value. The only variables exposed to the client are those that start with VITE_.

Syntax:

VITE_KEY_NAME = value

Example:

VITE_API_URL = https://api.example.com
VITE_APP_NAME = MyApp
env
.env

Approach 2: Directly in the Vite Configuration FIle

  • The Vite Configuration file (vite.config.js) supports direct usage of the environmental variables. This method helps to define variable specific to configuration.
  • The Vite Configuration file accesses environmental variables using process.env.

Syntax:

//vite.config.js:

import { defineConfig } from 'vite';
export default defineConfig({
define: {
__VARIABLE_NAME__: JSON.stringify(process.env.VARIABLE_NAME)
}
});

Approach 3: Accessing Environment Variables in your Code

After defining environment variables and adding a prefix of VITE_, you would be able to access them right from within your code by using import.meta.env.

Syntax:

import.meta.env.VITE_KEY_NAME

Example: You can add this code to any of your file to get the respective output.

JavaScript
console.log(import.meta.env.VITE_API_URL); 
console
console output

Next Article
How to Load environment variables from .env file using Vite?

V

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

Similar Reads

  • How To Set Environment Variables In Jenkins ?
    Jenkins is a widely used open-source automation server that facilitates continuous integration and continuous delivery (CI/CD) processes. One powerful feature of Jenkins is its capability to configure environment variables, which are important for various functions like defining parameters, paths, a
    6 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
  • Set environment variable in MATLAB
    Setting environment variables with the help of setenv() function. The setenv() function is used to set the specified value of an operating system environment variable. Here the environment variable "name" will be replaced with "value", where "name" and "value" is its parameters. Syntaxsetenv(name, v
    1 min read
  • How to Read Environment Variables in Scala?
    Scala stands for scalable language. It is an object-oriented language that provides support for functional programming approach as well. Everything in scala is an object e.g. - values like 1,2 can invoke functions like toString(). Scala is a statically typed language although unlike other statically
    3 min read
  • How to add environment variable in MacOS?
    While programmers work on different Programming Languages, they use to declare Variables to work on any certain piece of code. The Variables in general terms are used to store some values that can be again accessed in the future. There are some Operating System Variables present that are known as En
    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 Set Environment Variable in AWS Lambda ?
    AWS Lambda is a managed serverless deployment service of AWS that can be used for the implementation of various applications in the cloud. AWS lambda may use various environment variables for the execution of different operations. eg. Database Credentials, API Keys .etc. There are various ways we ca
    4 min read
  • Environment Variables in Java
    In Java, Environment variables are widely used by operating systems to deliver configuration data to applications. Environment variables are key/value pairs with both the key and the value being strings, similar to properties in the Java platform. What are Environment Variables in Java?In Java, Envi
    5 min read
  • Next.js Environment Variables
    Environment variables are a fundamental aspect of modern web development, allowing developers to configure applications based on the environment they are running in (development, testing, production, etc.). In Next.js, environment variables provide a flexible and secure way to manage configuration s
    3 min read
  • Next.js Environment Variables
    In this article, we are going to see how to use environment variables in Next.js. Environment variables in Next.js are a way to set configuration values that are used by your application. They can be used to store data such as the name of your company, the port your application will run on, or any o
    2 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