Vite

Configuring Vite environment variables and modes

Set environment precedence for development, staging, and production, load values in vite.config.ts, and verify what Vite embeds in the client bundle.

Configuring Vite environment variables and modes

I want the API endpoint and feature flags to be explicit when switching between local, staging, and production. Vite’s mode system controls which files supply those values, and the bundle shows what reaches the client.

The examples use Vite, TypeScript, and pnpm. The screenshots show the staging and production builds in the example project.

Know which environment API you are reading

process.env is available to Node.js. In browser code, Vite exposes import.meta.env, a Vite-specific extension of the standard import.meta object. The development server supplies its values, and the production build replaces eligible references with literal values.

1
2
3
4
// src/services/apiClient.ts
// Read environment values in browser code
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
const IS_DEBUG_MODE = import.meta.env.DEV;

The production transformation makes conditional code elimination possible. Once import.meta.env.DEV is replaced with false, the production bundler can remove an unreachable development branch.

1
2
3
4
5
6
7
8
9
// Source before the build
if (import.meta.env.DEV) {
  console.log("Endpoint:", import.meta.env.VITE_API_BASE_URL);
}

// After replacement in the production bundle
if (false) {
  console.log("Endpoint:", "https://api.namju.kim");
}

By default, Vite exposes environment variables with the VITE_ prefix to browser code alongside its built-in values. A prefix controls which values may be exposed. Anyone who can read the client bundle can read the ones you expose, so I put API endpoints and public feature flags there and leave credentialed operations on the server.

Choose a mode and trace which file wins

vite defaults to the development mode, and vite build defaults to production. Pass --mode staging when the build should load staging settings. Mode picks the environment files and affects import.meta.env.MODE. The operation is still a production build unless its build environment is configured differently.

1
2
3
4
# bash
# Commands to run through the package scripts
pnpm vite build --mode staging
pnpm vite build --mode production

The following diagram shows precedence from the highest-priority dotenv file to the default. Values that already exist in the process environment when Vite starts take precedence over any of these files.

flowchart TD
    subgraph EnvPriority["Dotenv precedence (highest to lowest)"]
        F1[".env.[mode].local (local mode overrides)"] --> F2[".env.[mode] (shared mode defaults)"]
        F2 --> F3[".env.local (local overrides for all modes)"]
        F3 --> F4[".env (shared defaults for all modes)"]
    end

For a staging build, the order within the file set is .env.staging.local, .env.staging, .env.local, then .env. I use the versioned files for shared defaults and keep private local overrides in ignored files. Restart the development server after editing dotenv files so it reloads them.

Build logs comparing Vite staging and production modes Figure 1. The staging and production builds selected different API endpoints and minification settings.

In this example, staging embeds https://api-staging.namju.kim and production embeds https://api.namju.kim. The production configuration also removes console calls through Terser, which accounts for part of the bundle size difference. Selecting a mode by itself does not activate that optimization.

Load values explicitly inside vite.config.ts

The config file runs before Vite automatically supplies dotenv values to the application. Existing shell variables are available through process.env, but values found only in a mode-specific dotenv file need explicit loading while the config is evaluated.

With the function form of defineConfig, read mode from the context and call loadEnv. The example uses the current project directory and an empty prefix to load values for config-side decisions such as choosing the proxy target.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// vite.config.ts
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig(({ mode }) => {
  // 1. Read the dotenv files for this mode from the working directory.
  // An empty prefix loads values regardless of whether they start with VITE_.
  const env = loadEnv(mode, process.cwd(), '');

  console.log(`[vite.config] Current Mode: ${mode}`);
  console.log(`[vite.config] Target API: ${env.VITE_API_BASE_URL}`);

  return {
    plugins: [react()],
    server: {
      port: 3000,
      // Use the environment value as the API proxy target
      proxy: {
        '/api': {
          target: env.VITE_API_BASE_URL || 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    define: {
      // Define an optional global constant
      __BUILD_TIMESTAMP__: JSON.stringify(new Date().toISOString())
    }
  };
});

Loading an environment value inside the config does not automatically put it in the client. Passing the value into define, a generated module, or another client-side declaration can expose it. Keep the proxy target configuration and any browser-exposed constants intentional.

Give the type checker the expected variables

I define the project’s known keys in src/vite-env.d.ts. An ambient declaration lets the IDE offer completions and helps document how the client uses each key.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/vite-env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  /** REST API base endpoint */
  readonly VITE_API_BASE_URL: string;
  /** Whether the local mock service worker is enabled */
  readonly VITE_ENABLE_MOCK: string;
  /** Sentry error tracking DSN */
  readonly VITE_SENTRY_DSN?: string;
  /** Application version */
  readonly VITE_APP_VERSION: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

The declaration is a compile-time contract. It does not write dotenv files or verify that a variable actually exists at deployment. Vite reads custom environment values as strings. Parse flags explicitly and validate required values where the application starts. Vite versions that support strictImportMetaEnv can additionally flag unknown keys when that opt-in is enabled.

Verify the values in the output

I inspect the generated files in dist/assets/ after a staging build. Search for the expected API hostname and confirm there are no references to the wrong environment. I then launch the preview server and watch an API request to verify its actual destination.

Terminal checks for the API URL embedded in Vite's generated JavaScript Figure 2. The expected staging URL is present in the bundle, and the preview server is ready for a runtime check.

Use direct static property access for client variables so the code makes the dependency apparent.

1
const apiUrl = import.meta.env.VITE_API_BASE_URL

Avoid assuming an arbitrary computed lookup such as import.meta.env[key] has the same build-time behavior as a direct reference. Confirm what the production output contains when using a more dynamic access pattern. Before shipping, check the selected mode, the process environment, the client values the build emits, and the behavior of the preview.

Next Generation Frontend Tooling
This post is licensed under CC BY 4.0 by the author.