javascriptreactjsenvironment-variablesvite

loading env variables in react app using vite


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?


Solution

  • 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