Preventing Firebase duplicates leads to the error of not being able to read the property 'apps'

Struggling to incorporate Firebase into a TypeScript/NextJS project, I have encountered difficulties. Despite successfully importing and initializing the app:

import * as firebase from "firebase/app";
import { collection, getDocs } from "firebase/firestore";

const firebaseConfig = ({
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
});

firebase.initializeApp(firebaseConfig);

Upon page reload, an error arises:

FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).

To address this issue, I substituted:

firebase.initializeApp(firebaseConfig);

with

if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
} else {
   firebase.app();
}

This alteration results in a

TypeError: Cannot read property 'length' of undefined
. The Intellisense for apps indicates
Property 'apps' does not exist on type
, leaving me uncertain about the next step. Any assistance would be greatly appreciated.

Answer №1

If you are working with version 9, the recommended approach is to utilize getApps for your testing needs:

import { getApps, initializeApp } from "firebase/app"

if (!getApps().length) initializeApp(firebaseConfig)

Visit this link for more information.

Answer №2

You should consider sticking with the syntax designed for versions 8.x and earlier of the Firebase SDKs, as it is more in line with your current setup. Version 9 presents a new, modular syntax that may require some adjustments - check out @jnpdx's reference for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring React Native Expo: A guide on selecting multiple documents from a collection using Firebase queries

Currently, I am implementing Firebase to synchronize my pet listings on the application for display in the following format: (IMAGE) Name Breed Age Shelter https://i.stack.imgur.com/y7Rpr.png But I'm facing a challenge trying to code this out b ...

Disabling the use of console.log() in a live environment

In an effort to disable console logs for production environments in my angular application, I implemented the code below. While it successfully suppresses logs in Chrome, IE 11 continues to display them. Here is the snippet from main.ts: if (environment. ...

What could be causing the TypeScript type error within this Effector effect subscriber?

Working on a front-end application utilizing React, Typescript, Effector, FetchAPI, and other technologies. Created an Effector effect to delete an item in the backend: export const deleteItemFX = createEffect({ handler: (id: string) => { return ...

Issue in Typescript: The type 'RegExpMatchArray' cannot be assigned to a parameter of type 'string'

Here is the code snippet I am working with: import { persistState } from 'redux-devtools'; const enhancer = compose( applyMiddleware(thunk, router, logger), DevTools.instrument(), persistState( window.location.href.match(/[?&]debu ...

Exploring the concept of object destructuring in Typescript with imports

Currently, I am in the process of developing the type system for @masala/parser. This allows me to customize the index.d.ts file to fit my needs. When using this as a user, I can: import masala from '@masala/parser' let {C, Stream, F} = masala; ...

What is the process for incorporating additional fields into Firebase?

I am looking to incorporate a fresh field similar to the example shown below, but I am unsure of how to proceed. In my previous attempt, I utilized a method called {merge: true}, yet encountered no success with resolving the issue at hand. Whenever I inp ...

Encountering issues while trying to deploy a Next JS 13 application on Google Cloud Platform's

Everything was functioning properly with Next version 12, however upon upgrading to Next 13 I encountered the following error. and current node version: "18.x.x" Next Js version: "13.2.1" Step #2: /app/node_modules/next/dist/build/index ...

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

What is the best way to determine the highest value?

How can I ensure that the data is displayed based on the condition c.date <= this.selectedReport.report_date? The current code snippet if (Math.max(...this.costs.map(c => c.date))){} seems to be causing an issue where no data is being displayed. What ...

Clerk and Vitest Errors in Unit Testing

Currently, I am tackling a project at my workplace that has a strict requirement for unit tests. To fulfill this requirement, I opted to utilize Vitest and integrated Clerk for authentication purposes. However, I've encountered two distinct issues alo ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

Error message: "The function app.functions is not a valid function in Angular Fire Functions

Currently, I am utilizing Angular v16 alongside Angular Fire v16 and Firebase v9. Following the instructions, I completed all the necessary setup steps including executing firebase login, firebase init, and converting the functions to typescript. Next, wi ...

Discovering specific values for an ID using API calls in Angular (Implementing CRUD Operations in Angular with API Integration)

My current project involves CRUD operations in Angular utilizing the API created in Laravel. I have successfully added and fetched values, but encountered an issue when attempting to update values using their respective IDs. This snippet is from my app.co ...

Comparison between the version of a particular dependency and the version of its dependent dependency

Imagine a scenario where I have dependency X version 1.0 and dependency Y version 1.0 defined in my package.json. Would there be any issues if Y requires X version 2.0 (as indicated in the package-lock.json) but I continue to use X version 1.0 in my code ...

Tips for modifying the type definition of a third-party library in a Vue project built with Create-Vue

After updating the Cesium library in my Vue project, I encountered some errors. This is the code snippet: camera.setView({ destination, orientation: { heading, pitch } }) The error message reads: Type '{ heading: number; pitch: number; }' i ...

Adjust the border color of the <input> element when it is clicked on

I'm currently working on a login screen for my next.js application and I've encountered an issue where the border color changes to a mixture of white and blue when I select an input field. https://i.stack.imgur.com/R2yKa.png I attempted to reso ...

Setting up nodemon with Next.js and Express: A Guide

Here is a snippet from my main server file: const express = require("express"); const next = require("next"); const port = parseInt(process.env.PORT, 10) || 3000; const dev = process.env.NODE_ENV !== "production"; const app = ...

What causes the disparity in outcomes between an API request using node-fetch versus the built-in fetch in Node.js?

I developed a node application that sends an API request to place a bet on Manifold, a fictional betting website. Using node-fetch successfully triggers the bet, but when relying on the built-in fetch function, it sometimes returns an outdated version of ...

Creating Typescript types based on the values of other props: A guide

Can the TypeScript prop type be dynamically changed based on the runtime value of another prop? For instance type MyComponent = { propA: boolean | string propB: typeof propA boolean ? number : string } Is it feasible to determine the prop type of p ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...