Home > Back-end >  Error when I use process.env with Vue and Vite
Error when I use process.env with Vue and Vite

Time:12-25

I'm coding a web application with Vue, Vue router, Vite and Firebase to handle the auth. To intialize my Firebase application I use the .env and to get the firebase variables (like VUE_APP_API_KEY, VUE_APP_AUTH_DOMAIN, etc...) in my firebase.js file I use process.env.VUE_APP_MY_VARIABLE. However when I go to my main page I've got an error in my browser's console.

Here is the error in the console:

Uncaught ReferenceError: process is not defined at firebase.js:6:13

So I've tried to use import.meta.env instead of process.env but for all my variables in the .env file, it returns me undefined. I've tried too to define all my variables in the vite.config.js like this but it still returns me undefined:

export default defineConfig({
  plugins: [vue()],
  define: {
    "process.env.VUE_APP_MY_VARIABLE": process.env.VUE_APP_MY_VARIABLE
  }
})

I'm sure that all my variables are indeed declare in the .env file because my IDE propose me all the good name with the auto-completion. In doubt I've tried to rename the .env file by .env.local but it's still the same.

Here is my firebase.js file's code:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth"
import { getFirestore } from "firebase/firestore"

const firebaseConfig = {
    apiKey: process.env.VUE_APP_API_KEY,
    authDomain: process.env.VUE_APP_AUTH_DOMAIN,
    projectId: process.env.VUE_APP_PROJECT_ID,
    storageBucket: process.env.VUE_APP_STORAGE_BUCKET,
    messagingSenderId: process.env.VUE_APP_MESSAGING_SENDER_ID,
    appId: process.env.VUE_APP_APP_ID
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);

export { auth, db };

So can anyone help me to solve my error ?

(PS: I apologize if my English wasn't perfect)

CodePudding user response:

Only variables prefixed with VITE_ are exposed. Source

Vite uses import.meta.env

  • Related