Search code examples
reactjsfirefoxchromiumvite

.env variables with Vite not changing in the browser


I have a React app that I have migrated to Vite from CRA for bundling/serving. Since I am re-using the API wrapper that communicates with the backend in other projects, I made it a library distributed via npm. The backend URL should be configurable from the frontend using the library, so with CRA I defined it from a .env file and accessing them from within the library using process.env.REACT_APP*. Now with Vite, I am trying to achieve the same thing, so in my library (that bundles with rollup) I am letting the library consumer set the backend URL by reading `import.meta.env.VITE_`, which in the consuming React app is stored in a .env file.

In principle, this is working, but sometimes it seems that env variables are cached somewhere, because my changes to them in the .env file are not always reflected in the version served by `npm start`, and inconsistently so between browsers: for some hours Firefox was using a stale env value, then it suddenly worked, and now Chromium is behaving equally weird, although Firefox is working now. Neither re-starting the dev server nor my PC (!) seems to be working. I am completely lost as to why this is happening and why it is arbitrarily happening in different browsers at different times across re-boots.


Solution

  • ***** UPDATE #2 *****

    So apparently, it seems like process.env had the variables after the build so I just ended up checking if it's PROD to use the process.env.VARIABLE_NAME, and if it's not PROD I use window.process.env.VARIABLE_NAME


    ***** UPDATE #1 *****

    Seems like it's working only when running localhost. Still checking why it won't work after the build. Will update you when I manage to solve it.


    For anyone who still faces this issue, I managed to solve it by installing vite-plugin.environment and importing it inside vite.config

    import EnvironmentPlugin from 'vite-plugin-environment';
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [react(), EnvironmentPlugin('all', { prefix: 'VITE_' })],
    
      // ... rest of your configuration
    })
    

    Then within the consumed package built using rollup, I changed process.env.VARIABLE_NAME to window.process.env.VARIABLE_NAME.

    It seems like it's working thanks to EnvironmentPlugin, which also injects the process.env inside window.