Developers using JavaScript or JavaScript-based frameworks typically add dotenv to their dependencies and put environment variables and secrets in a .env file, which can then be referenced using process.env.VARIABLE_NAME
, however anyone using Vite may come across an error stating that process is not defined
during runtime.
The way around this is to replace process
with import.meta
, and prefix and public-facing variables with VITE_
.
# .env
VITE_BASE_URL=https://api.example.com
# index.js
const products = await fetch(`${import.meta.env.VITE_BASE_URL}/products`)
The need to include the VITE_
prefix helps prevent accidentally leaking sensitive environment variables to the client, such as a database connection string. If you want to read more, check out the Vite documentation on environment files.