24

I´ve been through all the docs from vite, react.js and dev blogs, but I'm not getting it to work

I have a .env file which contains the following

VITE_API_KEY = XXX 

inside my firebase.js file I'm loading it like :

const firebaseConfig = {
  apiKey: import.meta.env.API_KEY,
   .....
   .....
}
// Initialize Firebase
const app = initializeApp(firebaseConfig);

but it appears as null, I've restarted the dev server, reinstalled node_modules (just in case) changed var prefixes to REACT_APP_XX, tried using process.env.XX global object, basically gone through all different ways to read vars from a .env file in react

I´ve also tried to clog it from a component but it has the same result

any suggestions/methods to solve this problem?

Forshank
  • 749
  • 1
  • 6
  • 15

3 Answers3

27

The environment variable name used in code must match the name set in the .env file:

// .env
VITE_API_KEY=abcd1234
   
// firebase.js
const firebaseConfig = {      
  apiKey: import.meta.env.VITE_API_KEY,
  ⋮
}

demo

tony19
  • 125,647
  • 18
  • 229
  • 307
26

finally solved this problem, the thing was that:

import.meta.env.VITE_XX

this env variable are statically replaced during production, not development, at least in my case I solved this by checking the mode by doing

 if(import.meta.env.MODE === "development"){
//use dev keys
}
else{
//use .env variables
}

when in production mode

import.meta.env.VITE_XX 

variables will load correctly, so you can add them as env variables in your deployment service and it will work fine. I've tested it with vercel and it worked

Forshank
  • 749
  • 1
  • 6
  • 15
15

It works if all variables start with VITE_

K Scandrett
  • 16,390
  • 4
  • 40
  • 65
wes
  • 191
  • 1
  • 4