Open In App

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
Article Tags :

Similar Reads