How can I initialize Firebase with environmental variables in Next.js without encountering a FirebaseError: "Firebase App named ‘[DEFAULT]’ already exists with different options or config (app/duplicate-app)" when I try to use .env.local file variables in my code to define the Firebase configuration, as shown in the example below?
const firebaseConfig = {
apiKey: process.env.APIKEY,
authDomain: process.env.AUTHDOMAIN,
projectId: process.env.PROJECTID,
storageBucket: process.env.STORAGEBUCKET,
messagingSenderId: process.env.MESSAGINGSENDERID,
appId: process.env.APPID
};
const app = initializeApp(firebaseConfig);
note i am using nextjs with jsx javascript not typescript and tailwindcss with firebase/firestore for the backend
2
Answers
To use environment variables in a Next.js application with Firebase, you can define your Firebase configuration object in a separate file, and then import it into your code. This way, you can avoid defining the configuration object with environment variables every time you use Firebase in your code, which can lead to duplication errors.
Here’s an example of how you can do this:
Create a new file called firebaseConfig.js in your project’s root
directory.
In this file, define your Firebase configuration object
using environment variables:
const firebaseConfig = {
apiKey: process.env.APIKEY,
authDomain: process.env.AUTHDOMAIN,
projectId: process.env.PROJECTID,
storageBucket: process.env.STORAGEBUCKET,
messagingSenderId: process.env.MESSAGINGSENDERID,
appId: process.env.APPID
};
export default firebaseConfig;
In your code, import the
firebaseConfig
object and use it to initialize your Firebase app:import { initializeApp } from ‘firebase/app’;
import firebaseConfig from ‘../path/to/firebaseConfig’;
const app = initializeApp(firebaseConfig);
Make sure to replace
../path/to/firebaseConfig
with the actual path to yourfirebaseConfig.js
file.By defining your Firebase configuration object in a separate file, you can avoid duplicating the Firebase app with different configuration options or config. This should ensure that your Firebase app is initialized correctly and you can use it without encountering any errors.
I’m a ReactJS developer and do not have any experience in NextJS. However, from the firebase error, it seems you are trying to initialize firebase multiple times or in multiple modules.
How I tackled this error (and hopefully it works for you), is by having a Firebase.js file seperate from other components, and doing my initialization and configuration in here, then any resource I need would be exported and then imported from the file where it is needed. For example in a project where I would need to use storage functions, I would do this
Firebase.js:
and then I can get this from any component as so
Component.js:
Hence I can do all my firebase initializing once.
Hopefully it works for NextJS 🙂