10

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_' }),
  ],
})

3
  • import.meta.REACT_APP_ID?
    – Konrad
    Commented Jul 14, 2023 at 16:13
  • 1
    I'm getting SyntaxError: Uncaught SyntaxError: Cannot use 'import.meta' outside a module
    – Don J
    Commented Jul 14, 2023 at 17:14
  • 1
    I'm trying to use it within the index.html file
    – Don J
    Commented Jul 14, 2023 at 17:16

3 Answers 3

17

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>
2
  • Thanks, this fixes my error but I guess I can't use it with the import EnvironmentPlugin from 'vite-plugin-environment'
    – Don J
    Commented Jul 15, 2023 at 10:16
  • I was using that plugin to make jest tests work with envs, is there a solution for that. when I use import.meta.env. All my jest unit tests fail
    – Don J
    Commented Jul 15, 2023 at 10:16
2

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

0
-1

In VITE project you should import env from import.meta.VITE_API_KEY

Remember! : While use VITE project your all env variables names are starting with VITE

for example:

VITE_API_KEY =randomKey ✅

API_KEY = randomKey ❌

4
  • Thanks but doing this still doesnt allow me use envs within the index.html file
    – Don J
    Commented Jul 14, 2023 at 17:17
  • index.html is not a programming language and you can't use it. env is not use in .js/ts/jsx/tsx files Commented Jul 14, 2023 at 17:26
  • I'm trying to use it within the script tag of my index.html file in a vite react project
    – Don J
    Commented Jul 14, 2023 at 17:53
  • Create React App is able to do this "%ENV_VAR%"
    – Don J
    Commented Jul 14, 2023 at 17:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.