Vite is a modern frontend build tool that differs from Webpack in its handling of environment variables. Unlike Webpack, Vite does not include the process.env global variable by default because it intentionally does not expose all environment variables to client-side code to enhance security. However, you can add and use environment variables by following these steps:
-
Create an environment variables file in the project root directory:
Typically, you can create a
.envfile to store your environment variables, or create environment-specific files such as.env.developmentor.env.production.shell# .env file VITE_API_URL=http://localhost:3000Vite requires all environment variables in
.envfiles to start withVITE_so that it knows which variables can be exposed to the browser. -
Access your environment variables:
In your JavaScript or TypeScript code, you can access environment variables using
import.meta.env.javascriptconsole.log(import.meta.env.VITE_API_URL);Vite will replace
import.meta.env.VITE_API_URLwith the actual environment variable value during the build process. -
Type support:
If you use TypeScript, declare your environment variables in the
env.d.tsfile for better type support:typescript/// <reference types="vite/client" /> interface ImportMetaEnv { readonly VITE_API_URL: string; // Add more environment variables here } interface ImportMeta { readonly env: ImportMetaEnv; } -
Using environment variables in
vite.config.jsorvite.config.ts:To access environment variables in the Vite configuration file, use
process.envor theloadEnvmethod:javascriptimport { defineConfig, loadEnv } from 'vite'; export default ({ mode }) => { // When accessing environment variables in the configuration file process.env = {...process.env, ...loadEnv(mode, process.cwd())}; // Use environment variables in the configuration console.log(process.env.VITE_API_URL); return defineConfig({ // Configuration }); };
Ensure you set the correct environment variables when deploying your application. For platforms like Vercel, Netlify, or similar, set environment variables in their control panels. If deploying on your own server, configure these variables in the server environment.
Additionally, do not store keys or sensitive information in the .env file unless you are certain they will not be compiled into client-side code. Any environment variables compiled into client-side code can be viewed by users.