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