How Can I Use Vite Env Variables in vite.config.js?
Last Updated :
09 Sep, 2024
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
How Can I Use Vite Env Variables in vite.config.jsCommon 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
- 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.
- 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. - Type Coercion: Be mindful of type coercion when using environment variables. Use JSON.stringify() for strings or parse values if needed.
- 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.
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
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 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
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 use CSS variables with TailwindCSS ?
Tailwind CSS  allows users to predefined classes instead of using the pure CSS properties. We have to install the Tailwind CSS.  Create the main CSS file (Global.css) which will look like the below code. Global.css: In the following code, the entire body is wrapped into a single selector. The entir
1 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 declare variables in different ways in JavaScript?
In JavaScript, variables can be declared using keywords like var, let, or const, each keyword is used in some specific conditions. Understanding these declarations is crucial for managing variable lifetimes and avoiding unintended side effects in code. Table of Content JavaScript varJavaScript letJa
2 min read
How to Host ReactJS Websites on Vercel with Environment Variables ?
In this article, we will learn how to host our ReactJs projects on Vercel and use Environment Variables in this tutorial. Vercel is a platform for developers to deploy and host their projects online, where they can showcase their skills to others. What is an Environment Variable? We conceal API keys
4 min read