Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining process.env variables in my Vite Config and consuming them in client-side scripts

A list of environment variables are available to my Node/FE (Astro based) application via process.env. I would like to make these also available automatically to my client-side scripts (SSR page, Astro Framework).

Vite offers the possibility to define new global env variables which to my understanding can be available on runtime. This would in theory allow me to use process.env inside my vite.config, and map these to runtime variables, which I can directly consume from my scripts via import.meta.env. Is that accurate?

https://vitejs.dev/config/#using-environment-variables-in-config

This is what I'm trying:

    // vite config
    define: {
      stage: process.env.NODE_ENV,
    },

And from my client-side script:

console.log(import.meta.env.stage)

Unfortunately, my log is undefined.

like image 815
George Katsanos Avatar asked Aug 31 '25 01:08

George Katsanos


2 Answers

  • first thing env variables in vite are statically replaced

ref : https://vitejs.dev/guide/env-and-mode.html#production-replacement

  • client is what runs on the browser where there is no environment, the env in only server side.
  • what vite does for the client is to replace with the value and ship the code to the client values already replaced
  • the reason it did not work for you is that, for security reason, vite restricts server env vars to client replacements only for ones having a special prefix. default prefix is 'VITE_XXX'

ref : https://vitejs.dev/config/shared-options.html#envprefix

Example

  • call an environment variable VITE_STAGE (or VITE_stage I guess should work)
  • assign value e.g. "True"
  • write in client script console.log(import.meta.env.VITE_STAGE)
  • server ships to client console.log("True")

Note1 : the client browser does not know import.meta.env.VITE_STAGE e.g. on browser debug console, it is Vite that replaced the expression on server side with the value

Note2 : all of this is static on build if what was intended was dynamic changing on runtime then see this question https://stackoverflow.com/a/74840400/1324481

like image 172
wassfila Avatar answered Sep 02 '25 15:09

wassfila


You can try,

define: {
  'import.meta.env.stage': process.env.NODE_ENV,
},

Unfortunately, I can't find any document about this.

like image 38
foxiris Avatar answered Sep 02 '25 15:09

foxiris