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:
.envfiles must be in the project root, not thesrcdirectory - Server restart needed: Changes to
.envfiles require restarting the development server - Wrong access method: Using
process.envinstead ofimport.meta.envin client code
Basic Setup
Create a .env file in your project root:
VITE_TEST_VAR=123F
VITE_API_KEY=your_api_key_hereAccess these variables in your application:
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:
// 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:
// 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:
VITE_MY_VAR=${SYSTEM_ENV_VAR}
VITE_MY_VAR_WITH_DEFAULT=${SYSTEM_ENV_VAR:-default_value}Recommended Solution
For most use cases, the standard Vite approach works best:
- Prefix variables with
VITE_in your.envfiles - Access via
import.meta.envin client-side code - Use
loadEnv()for server-side or build configuration
// Standard approach for client-side access
const apiKey = import.meta.env.VITE_API_KEYAlternative Approach (Use with Caution)
If you need to access environment variables without the VITE_ prefix in client code, you can modify the Vite configuration:
// 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
// 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:
- Verify file location:
.envfiles must be in the project root - Check variable prefixes: Must start with
VITE_(or your custom prefix) - Restart the dev server:
npm run devafter changing.envfiles - 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:
console.log('Environment variables:', import.meta.env)Best Practices
- Never commit sensitive data: Add
.envto your.gitignore - Use different files for different environments:
.env- default.env.development- development overrides.env.production- production overrides
- Provide fallback values for optional variables
- Validate required variables at application startup
By following these guidelines, you'll ensure your Vite application properly handles environment variables across different deployment environments.