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

In tsconfig.json, the compiler is not utilizing other tsconfig.json files when using the "extends"

I'm attempting to streamline my project by breaking up my tsconfig.json into separate files. I have one for the source files and another for the tests. However, when I utilize the extends field, it seems that only the base tsconfig.json is being utili ...

Is it possible to identify in Next.js whether scrollRestoration was triggered, or if the back button was pressed?

I've been utilizing the scrollRestoration functionality within Next.js to save and restore the page position whenever a user navigates using the back button. However, I've encountered an issue with it not restoring the horizontal scroll position ...

Ways to access the chosen value from Ionic's popover modal

I have been working on a simple Ionic 4 Angular app and I am using an Ionic popover modal. The code below shows how I open the popover modal in my application: //home.page.ts async openModal(ev: Event) { const modal = await this.popoverController.create({ ...

Interpret information in Angular 2 using Typescript

Just starting with Angular (IONIC) and need help. How can I extract the userId or id from this code? his.response = data. //Looking for guidance on accessing Json keys Response : { "userId": 1, "id": 1, "title": "sunt aut facere repellat providen ...

Subtracted TypeScript concept

Is it possible to create a modified type in Typescript for React components? import {Component, ComponentType} from 'react'; export function connect<S, A>(state: () => S, actions: A){ return function createConnected<P>(componen ...

Encountered an issue while building Next.js in a Docker container, although it runs smoothly when

I am facing an issue with building my nextjs app in docker, although it runs without any errors locally. I have added output: 'standalone' to my nextjs config and the project is using yarn. The Dockerfile I am using is identical to the one found ...

Surprising findings when attempting to log error messages in the console within Next-Auth

I am currently developing a Next.js application with Next-auth.js for authentication. This app is hosted on Vercel. However, I encountered some errors when trying to access my app, as shown below: Failed to load resource: the server responded with a sta ...

Error: Property cannot be read after page refresh or modification

Upon refreshing or running the project for the first time, I encounter the error: TypeError: Cannot read property 'statements' of undefined This issue is perplexing as the data renders correctly but it appears that the connection is failing. ...

What steps are needed to generate a production version of a TypeScript monorepo application that can be deployed to an Azure Function App?

I've been grappling with understanding Typescript project references and their intended use in a production build, especially for an Azure Function App. I'm not utilizing any monorepo functionality at the package manager level, such as npm worksp ...

What is the best way to interact with and modify the relationships of "many-to-many" fields in my database table?

As someone who is new to nestjs, I am working with two entities: @Entity({ name: "Books" }) @ObjectType() export class Book { @PrimaryGeneratedColumn() @Field() id: number; @Column() @Field() title: string; @ManyToMany(() => Auth ...

typescript error is not defined

While browsing online, I came across a post discussing how to transfer data from an MVC model to a .ts file. The suggestion was to include the following code: <script type="text/javascript"> var testUrl = @Html.Raw(Json.Encode(Model.testUrl) ...

TypeScript causing issues when multiple selectors are used

Currently, I have a function that allows me to search for HTML elements based on text content: function findElementsByText(text: string): HTMLElement[] { const selectors = 'button' // This conditional statement ensures that an empty text quer ...

When implementing `redux-observable` with NextJS, the `HYDRATION` action may not properly receive the server payload

Packages: redux-observable@2.0.0-rc.2 rxjs latest universal-rxjs-ajax dev branch next-redux-wrapper latest next.js latest I am working on a simple Page with getStaticProps: export const getStaticProps = wrapper.getStaticProps((store) => async (ctx) =& ...

Retrieve targeted data from the database using AngularJS and Firebase

Apologies for bothering you with this, I have spent countless hours searching for a solution but I've hit a roadblock. I'm on the verge of giving up on working with angularjs and firebase because I just can't seem to grasp it.. I am attempt ...

Nest is having trouble resolving dependencies for this service

Can multiple MongoDB models be injected into one resolver and used? I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule: @Module({ imports: [MongooseModule.forFeature([{name: 'Post&apos ...

Challenges with date formatting arise for Spanish speakers when the date returns as NaN or an Invalid

I have been working on an Angular app Objective: My aim is to allow users to input dates in Spanish format (DD/MM/YYYY) and display them as such, while converting them back to English format when saving the data to the Database. Issue: One problem I enco ...

Unable to emphasize the navigation menu for the current page within the Antd menu component

My objective is to use the ant design Menu component to highlight the navigation menu item of the current page. However, it seems that no matter which page I am on, the menu item does not get highlighted. Below is my code for the navigation menu. import ...

The table is failing to display the values contained within the array

My users list is successfully retrieved from the API and I can see the data in my console. However, when I attempt to map it and display it as a table, it doesn't seem to work as expected. This is the component I'm working with: interface IUser { ...

What is the best way to retrieve the name of a static method within a class?

In my code, I am logging multiple messages in a static method and I want to use the method name as context. However, I do not want to create a separate variable called `context` and assign the function/method name to it. I would like to be able to access ...

Error TS2307: Module 'calculator' could not be located

Running a Sharepoint Framework project in Visual Studio Code: This is the project structure: https://i.stack.imgur.com/GAlsX.png The files are organized as follows: ComplexCalculator.ts export class ComplexCalculator { public sqr(v1: number): number ...