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
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects