Skip to content

Environment Variables in Vite

Vite provides built-in support for environment variables, but understanding how to properly configure and access them is essential for a smooth development experience.

The Core Issue

When using Vite, environment variables prefixed with VITE_ are automatically exposed to your client-side code through import.meta.env. However, variables without this prefix remain inaccessible by default for security reasons.

Common Mistakes

WARNING

Several common issues can prevent environment variables from working correctly:

  • Missing VITE_ prefix: Variables must be prefixed with VITE_
  • Incorrect file location: .env files must be in the project root, not the src directory
  • Server restart needed: Changes to .env files require restarting the development server
  • Wrong access method: Using process.env instead of import.meta.env in client code

Basic Setup

Create a .env file in your project root:

env
VITE_TEST_VAR=123F
VITE_API_KEY=your_api_key_here

Access these variables in your application:

javascript
console.log(import.meta.env.VITE_TEST_VAR); // "123F"
console.log(import.meta.env.VITE_API_KEY); // "your_api_key_here"

Advanced Configuration

Custom Environment Prefixes

You can customize the prefix using envPrefix in your Vite config:

javascript
// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  envPrefix: 'CUSTOM_', // Now CUSTOM_ variables will be exposed
  // ... other config
})

SECURITY WARNING

Never set envPrefix to an empty string (''), as this would expose all environment variables to the client, potentially leaking sensitive information.

Accessing Environment Variables in vite.config.js

To use environment variables within your Vite configuration file:

javascript
// vite.config.js
import { defineConfig, loadEnv } from 'vite'

export default ({ mode }) => {
  // Load environment variables
  const env = loadEnv(mode, process.cwd(), '')
  
  return defineConfig({
    // Access variables via env object
    define: {
      __API_URL__: JSON.stringify(env.VITE_API_URL)
    },
    // ... other config
  })
}

Accessing System Environment Variables

You can reference system environment variables in your .env file:

env
VITE_MY_VAR=${SYSTEM_ENV_VAR}
VITE_MY_VAR_WITH_DEFAULT=${SYSTEM_ENV_VAR:-default_value}

For most use cases, the standard Vite approach works best:

  1. Prefix variables with VITE_ in your .env files
  2. Access via import.meta.env in client-side code
  3. Use loadEnv() for server-side or build configuration
javascript
// Standard approach for client-side access
const apiKey = import.meta.env.VITE_API_KEY

Alternative Approach (Use with Caution)

If you need to access environment variables without the VITE_ prefix in client code, you can modify the Vite configuration:

javascript
// vite.config.js
import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  
  const sanitizedEnv = Object.keys(env).reduce((acc, key) => {
    // Sanitize key names for JavaScript usage
    const sanitizedKey = key.replace(/[^a-zA-Z0-9_]/g, '_')
    acc[`process.env.${sanitizedKey}`] = JSON.stringify(env[key])
    return acc
  }, {})
  
  return {
    define: sanitizedEnv,
    // ... other config
  }
})

PERFORMANCE NOTE

This approach exposes all environment variables to the client bundle, which may have security and performance implications. Use judiciously.

Framework-Specific Configuration

For SvelteKit

javascript
// vite.config.js
import { sveltekit } from '@sveltejs/kit/vite'
import { defineConfig, loadEnv } from 'vite'

export default ({ mode }) => {
  process.env = { ...process.env, ...loadEnv(mode, process.cwd()) }
  
  return defineConfig({
    plugins: [sveltekit()]
  })
}

Troubleshooting

If your environment variables aren't working:

  1. Verify file location: .env files must be in the project root
  2. Check variable prefixes: Must start with VITE_ (or your custom prefix)
  3. Restart the dev server: npm run dev after changing .env files
  4. Confirm variable names: Match exactly what you're accessing in code

DEVELOPMENT TIP

During development, you can temporarily add debug code to verify variables are loading correctly:

javascript
console.log('Environment variables:', import.meta.env)

Best Practices

  1. Never commit sensitive data: Add .env to your .gitignore
  2. Use different files for different environments:
    • .env - default
    • .env.development - development overrides
    • .env.production - production overrides
  3. Provide fallback values for optional variables
  4. Validate required variables at application startup

By following these guidelines, you'll ensure your Vite application properly handles environment variables across different deployment environments.