.env Files

Vite automatically makes environment variables defined in .env files available at import.meta.env, see Vite's docs about .env files.

Note that:

  • It only works for environment variables that are prefixed with VITE_ (for security reasons).
  • It only works for files processed by Vite. (All following files and their imports: *.page.js, *.page.server.js, *.page.client.js, *.page.route.js.) For files not processed by Vite (e.g. Express.js server code) we can use a Node.js tool such as dotenv (all browser files are always processed by Vite):
    // server.js
    if (!isProduction) {
      require('dotenv').config() // npm install dotenv