skip to Main Content

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

2

Answers


  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 ❌

    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search