Home > Software engineering >  Firebase config breaks when `projectId` is from environment variable
Firebase config breaks when `projectId` is from environment variable

Time:11-22

I'm experiencing a really odd issue with my Firebase config object and Vercel environment variables.

I can build up my entire Firebase config object with Vercel environment variables but if I use an environment variable for the value of projectId it breaks the entire configuration.

My config follows this format:

const firebaseConfig = {
    apiKey: `${process.env.FIREBASE_apiKEY}`,
    authDomain: `${process.env.FIREBASE_authDomain}`,
    projectId: "my-project-id-here",
    storageBucket: `${process.env.FIREBASE_storageBucket}`,
    messagingSenderId: `${process.env.FIREBASE_messagingSenderId}`,
    appId: `${process.env.FIREBASE_appId}`,
    measurementId: `${process.env.FIREBASE_measurementId}`
};

I then initialize Firebase with the object like so:

const app = initializeApp(firebaseConfig)

The above works, yet if I change the value of projecId to

`${process.env.FIREBASE_projectId}`

to match the others, I get FirebaseError: Failed to get document because the client is offline.

I've verified the value of process.env.FIREBASE_projectId is correct in the .env file and that the value comes out correct in firebaseConfig, yet the only time I don't get the error is when I hard code the value in a string.

CodePudding user response:

If you are using nextjs, use NEXT_PUBLIC prefix for your environment variables

 const firebaseConfig = {
   apiKey: `${process.env.NEXT_PUBLIC_FIREBASE_APIKEY}`,
   authDomain: `${process.env.NEXT_PUBLIC_FIREBASE_AUTHDOMAIN}`,
   projectId: `${process.env.NEXT_PUBLIC_FIREBASE_PROJECTID}`,
   storageBucket: `${process.env.NEXT_PUBLIC_FIREBASE_STORAGEBUCKET}`,    
   messagingSenderId:`${process.env.NEXT_PUBLIC_FIREBASE_MESSAGINGSENDERID}`,
   appId: `${process.env.NEXT_PUBLIC_FIREBASE_APPID}`,
   measurementId: `${process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENTID}`
     };
  • Related