Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use env in index.html within a react vite application

I'm trying to access an env variable from my index.html file.

The code below seems to work in CRA but doesnt work with my vite, react project setup

const APP_ID = '%REACT_APP_ID%'

    <script>
      //Set your APP_ID
      const APP_ID = '%REACT_APP_ID%'

     ....

    </script>

my vite config file

import { defineConfig, splitVendorChunkPlugin } from 'vite'
import react from '@vitejs/plugin-react'
import EnvironmentPlugin from 'vite-plugin-environment'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    splitVendorChunkPlugin(),
    react(),
    EnvironmentPlugin('all', { prefix: 'REACT_APP_' }),
  ],
})

like image 631
Don J Avatar asked Sep 10 '25 20:09

Don J


2 Answers

Replacing environment variables in HTML files is supported since Vite 4.2.0.

Define environment variables with the VITE_ prefix, and wrap it between % in the HTML file.

For example:

<div>%VITE_SOME_KEY%</div>
like image 177
Unmitigated Avatar answered Sep 13 '25 09:09

Unmitigated


You should to use only "%YOUR_VAR%" like this:

<script type="text/javascript">
    const flag = "%VITE_TRACKING_ID%" 
          if (flag) {
            ...
</script>

have in mind you would need to update your Vite 4.2.0 as commented @Unmitigated

this is the thread to fix https://github.com/vitejs/vite/issues/3105#issuecomment-1441947641

like image 44
rnewd_user Avatar answered Sep 13 '25 09:09

rnewd_user