Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The default Firebase app already exists. This means you called initializeApp() more than once #1532

Closed
tolotrasamuel opened this issue Jul 20, 2019 · 19 comments

Comments

@tolotrasamuel
Copy link

[REQUIRED] Environment info

firebase-tools: 7.1.0

Platform: Windows 10

[REQUIRED] Test case

import * as functions from 'firebase-functions';
import express from 'express';
import admin from "firebase-admin"
admin.initializeApp(functions.config())
console.log('Firebase Environment setup success')
const app1 = express()
app1.get("*", (request, response) => {
    response.send("bar")
})
const foo = functions.https.onRequest(app1)
module.exports = {
    foo
}

[REQUIRED] Steps to reproduce

Run
firebase emulators:start --only functions
visit the url of the function on your browser

[REQUIRED] Expected behavior

initializeApp should be called only once

[REQUIRED] Actual behavior

initializeApp is called everytime the url is called

! Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name. at FirebaseAppError.FirebaseError [as constructor] (C:\Users\Business\PhpstormProjects\gantt-flexx\node-server\node_modules\firebase-admin\lib\utils\error.js:42:28) at FirebaseAppError.PrefixedFirebaseError [as constructor] (C:\Users\Business\PhpstormProjects\gantt-flexx\node-server\node_modules\firebase-admin\lib\utils\error.js:88:28) at new FirebaseAppError (C:\Users\Business\PhpstormProjects\gantt-flexx\node-server\node_modules\firebase-admin\lib\utils\error.js:122:28) at FirebaseNamespaceInternals.initializeApp (C:\Users\Business\PhpstormProjects\gantt-flexx\node-server\node_modules\firebase-admin\lib\firebase-namespace.js:68:23) at FirebaseNamespace.initializeApp (C:\Users\Business\PhpstormProjects\gantt-flexx\node-server\node_modules\firebase-admin\lib\firebase-namespace.js:392:30) at Proxy. (C:\Users\Business\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:338:51) at C:\Users\Business\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:641:30 at Generator.next () at fulfilled (C:\Users\Business\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:4:58) at process._tickCallback (internal/process/next_tick.js:68:7) ! Your function was killed because it raised an unhandled error.

@samtstern
Copy link
Contributor

@tolotrasamuel I am not sure what causes this issue but I think it will be fixed as soon as this PR is released since we no longer call admin.initializeApp() for you:
#1479

To be sure, could you run firebase --debug emulators:start --only functions and show me all of the logs?

@tolotrasamuel
Copy link
Author

>  Firebase Environment setup success
[2019-07-24T09:07:05.128Z] Accepted request GET /galvanic-pulsar-158719/us-central1/foo/ -
-> foo
[2019-07-24T09:07:13.057Z] [runtime-status] Functions runtime initialized. {"cwd":"C:\\Use
rs\\Business\\PhpstormProjects\\gantt-flexx\\node-server","node_version":"10.15.0"}
i  functions: Beginning execution of "foo"
[2019-07-24T09:07:13.061Z] [runtime-status] Disabled runtime features: undefined {}
[2019-07-24T09:07:13.075Z] [runtime-status] Resolved module firebase-admin {"declared":tru
e,"installed":true,"version":"8.2.0","resolution":"C:\\Users\\Business\\PhpstormProjects\\
gantt-flexx\\node-server\\node_modules\\firebase-admin\\lib\\index.js"}
[2019-07-24T09:07:13.082Z] [runtime-status] Resolved module firebase-functions {"declared"
:true,"installed":true,"version":"3.1.0","resolution":"C:\\Users\\Business\\PhpstormProjec
ts\\gantt-flexx\\node-server\\node_modules\\firebase-functions\\lib\\index.js"}
[2019-07-24T09:07:14.273Z] [runtime-status] Found google-gax at C:\Users\Business\Phpstorm
Projects\gantt-flexx\node-server\node_modules\google-gax\build\src\index.js {}
[2019-07-24T09:07:14.277Z] [runtime-status] Outgoing network have been stubbed. [{"name":"
http","status":"mocked"},{"name":"http","status":"mocked"},{"name":"https","status":"mocke
d"},{"name":"https","status":"mocked"},{"name":"net","status":"mocked"},{"name":"google-ga
x","status":"mocked"}]
[2019-07-24T09:07:14.893Z] [runtime-status] Checked functions.config() {"config":{}}
[2019-07-24T09:07:14.907Z] [runtime-status] Resolved module firebase-functions {"declared"
:true,"installed":true,"version":"3.1.0","resolution":"C:\\Users\\Business\\PhpstormProjec
ts\\gantt-flexx\\node-server\\node_modules\\firebase-functions\\lib\\index.js"}
[2019-07-24T09:07:14.940Z] [runtime-status] Resolved module firebase-admin {"declared":tru
e,"installed":true,"version":"8.2.0","resolution":"C:\\Users\\Business\\PhpstormProjects\\
gantt-flexx\\node-server\\node_modules\\firebase-admin\\lib\\index.js"}
[2019-07-24T09:07:14.957Z] [runtime-status] firebase-admin has been stubbed. {"adminResolu
tion":{"declared":true,"installed":true,"version":"8.2.0","resolution":"C:\\Users\\Busines
s\\PhpstormProjects\\gantt-flexx\\node-server\\node_modules\\firebase-admin\\lib\\index.js
"}}
[2019-07-24T09:07:15.547Z] [runtime-status] config() parent accessed! {"parentKey":"creden
tial","parentConfig":{"credential":{"credential_":{"httpClient":{"retry":{"maxRetries":4,"
statusCodes":[503],"ioErrorCodes":["ECONNRESET","ETIMEDOUT"],"backOffFactor":0.5,"maxDelay
InMillis":60000}}}}}}
[2019-07-24T09:07:15.549Z] [runtime-status] config() parent accessed! {"parentKey":"creden
tial","parentConfig":{"credential":{"credential_":{"httpClient":{"retry":{"maxRetries":4,"
statusCodes":[503],"ioErrorCodes":["ECONNRESET","ETIMEDOUT"],"backOffFactor":0.5,"maxDelay
InMillis":60000}}}}}}
>  Firebase Environment setup success
[2019-07-24T09:07:15.562Z] [runtime-status] Trigger "foo" has been found, beginning invoca
tion! {}
[2019-07-24T09:07:15.563Z] [runtime-status]  {"httpsTrigger":{},"name":"foo","entryPoint":
"foo"}
[2019-07-24T09:07:15.565Z] [runtime-status] Running foo in mode HTTPS {}
!  Error: The default Firebase app already exists. This means you called initializeApp() m
ore than once without providing an app name as the second argument. In most cases you only
 need to call initializeApp() once. But if you do want to initialize multiple apps, pass a
 second argument to initializeApp() to give each app a unique name.
    at FirebaseAppError.FirebaseError [as constructor] (C:\Users\Business\PhpstormProjects
\gantt-flexx\node-server\node_modules\firebase-admin\lib\utils\error.js:42:28)
    at FirebaseAppError.PrefixedFirebaseError [as constructor] (C:\Users\Business\Phpstorm
Projects\gantt-flexx\node-server\node_modules\firebase-admin\lib\utils\error.js:88:28)
    at new FirebaseAppError (C:\Users\Business\PhpstormProjects\gantt-flexx\node-server\no
de_modules\firebase-admin\lib\utils\error.js:122:28)
    at FirebaseNamespaceInternals.initializeApp (C:\Users\Business\PhpstormProjects\gantt-
flexx\node-server\node_modules\firebase-admin\lib\firebase-namespace.js:68:23)
    at FirebaseNamespace.initializeApp (C:\Users\Business\PhpstormProjects\gantt-flexx\nod
e-server\node_modules\firebase-admin\lib\firebase-namespace.js:392:30)
    at Proxy.<anonymous> (C:\Users\Business\AppData\Roaming\npm\node_modules\firebase-tool
s\lib\emulator\functionsEmulatorRuntime.js:338:51)
    at C:\Users\Business\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\func
tionsEmulatorRuntime.js:641:30
    at Generator.next (<anonymous>)
    at fulfilled (C:\Users\Business\AppData\Roaming\npm\node_modules\firebase-tools\lib\em
ulator\functionsEmulatorRuntime.js:4:58)
    at process._tickCallback (internal/process/next_tick.js:68:7)
!  Your function was killed because it raised an unhandled error

@google-oss-bot google-oss-bot added Needs: Attention and removed Needs: Author Feedback Issues awaiting author feedback labels Jul 24, 2019
@tolotrasamuel
Copy link
Author

@samtstern It seems like the function is running twice that's why it throws the error

The default Firebase app already exists. This means you called initializeApp() more than once

By the way I am using

   "firebase-admin": "^8.2.0",
    "firebase-functions": "^3.1.0",

And

  "devDependencies": {
    "@firebase/testing": "^0.11.4",

@samtstern
Copy link
Contributor

@tolotrasamuel could you try replacing this:

admin.initializeApp(functions.config())

With just this:

admin.initializeApp()

@tolotrasamuel
Copy link
Author

I already tried. Exact same error @samtstern

i  functions: Beginning execution of "foo"
[2019-07-24T16:34:16.281Z] [runtime-status] Disabled runtime features: undefined {}
[2019-07-24T16:34:16.291Z] [runtime-status] Resolved module firebase-admin {"declared":tr
ue,"installed":true,"version":"8.2.0","resolution":"C:\\Users\\Business\\PhpstormProjects
\\gantt-flexx\\node-server\\node_modules\\firebase-admin\\lib\\index.js"}
[2019-07-24T16:34:16.296Z] [runtime-status] Resolved module firebase-functions {"declared
":true,"installed":true,"version":"3.1.0","resolution":"C:\\Users\\Business\\PhpstormProj
ects\\gantt-flexx\\node-server\\node_modules\\firebase-functions\\lib\\index.js"}
[2019-07-24T16:34:16.980Z] [runtime-status] Found google-gax at C:\Users\Business\Phpstor
mProjects\gantt-flexx\node-server\node_modules\google-gax\build\src\index.js {}
[2019-07-24T16:34:16.981Z] [runtime-status] Outgoing network have been stubbed. [{"name":
"http","status":"mocked"},{"name":"http","status":"mocked"},{"name":"https","status":"moc
ked"},{"name":"https","status":"mocked"},{"name":"net","status":"mocked"},{"name":"google
-gax","status":"mocked"}]
[2019-07-24T16:34:17.110Z] [runtime-status] Checked functions.config() {"config":{}}
[2019-07-24T16:34:17.113Z] [runtime-status] Resolved module firebase-functions {"declared
":true,"installed":true,"version":"3.1.0","resolution":"C:\\Users\\Business\\PhpstormProj
ects\\gantt-flexx\\node-server\\node_modules\\firebase-functions\\lib\\index.js"}
[2019-07-24T16:34:17.117Z] [runtime-status] Resolved module firebase-admin {"declared":tr
ue,"installed":true,"version":"8.2.0","resolution":"C:\\Users\\Business\\PhpstormProjects
\\gantt-flexx\\node-server\\node_modules\\firebase-admin\\lib\\index.js"}
[2019-07-24T16:34:17.125Z] [runtime-status] firebase-admin has been stubbed. {"adminResol
ution":{"declared":true,"installed":true,"version":"8.2.0","resolution":"C:\\Users\\Busin
ess\\PhpstormProjects\\gantt-flexx\\node-server\\node_modules\\firebase-admin\\lib\\index
.js"}}
>  Firebase Environment setup success
[2019-07-24T16:34:17.453Z] [runtime-status] Trigger "foo" has been found, beginning invoc
ation! {}
[2019-07-24T16:34:17.454Z] [runtime-status]  {"httpsTrigger":{},"name":"foo","entryPoint"
:"foo"}
[2019-07-24T16:34:17.456Z] [runtime-status] Running foo in mode HTTPS {}
!  Error: The default Firebase app already exists. This means you called initializeApp()
more than once without providing an app name as the second argument. In most cases you on
ly need to call initializeApp() once. But if you do want to initialize multiple apps, pas
s a second argument to initializeApp() to give each app a unique name.
    at FirebaseAppError.FirebaseError [as constructor] (C:\Users\Business\PhpstormProject
s\gantt-flexx\node-server\node_modules\firebase-admin\lib\utils\error.js:42:28)
    at FirebaseAppError.PrefixedFirebaseError [as constructor] (C:\Users\Business\Phpstor
mProjects\gantt-flexx\node-server\node_modules\firebase-admin\lib\utils\error.js:88:28)
    at new FirebaseAppError (C:\Users\Business\PhpstormProjects\gantt-flexx\node-server\n
ode_modules\firebase-admin\lib\utils\error.js:122:28)
    at FirebaseNamespaceInternals.initializeApp (C:\Users\Business\PhpstormProjects\gantt
-flexx\node-server\node_modules\firebase-admin\lib\firebase-namespace.js:68:23)
    at FirebaseNamespace.initializeApp (C:\Users\Business\PhpstormProjects\gantt-flexx\no
de-server\node_modules\firebase-admin\lib\firebase-namespace.js:392:30)
    at Proxy.<anonymous> (C:\Users\Business\AppData\Roaming\npm\node_modules\firebase-too
ls\lib\emulator\functionsEmulatorRuntime.js:338:51)
    at C:\Users\Business\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\fun
ctionsEmulatorRuntime.js:641:30
    at Generator.next (<anonymous>)
    at fulfilled (C:\Users\Business\AppData\Roaming\npm\node_modules\firebase-tools\lib\e
mulator\functionsEmulatorRuntime.js:4:58)
    at process._tickCallback (internal/process/next_tick.js:68:7)
!  Your function was killed because it raised an unhandled error.

@samtstern
Copy link
Contributor

@tolotrasamuel we just released firebase-tools version 7.2.0 about 5 minutes ago. That contains the fix for #1479 that I was mentioning. Could you upgrade (npm install -g firebase-tools@7.2.0) and see if you still have this issue? If so please provide debug logs again. Thanks for your help and patience!

@tolotrasamuel
Copy link
Author

tolotrasamuel commented Jul 24, 2019 via email

@samtstern
Copy link
Contributor

@tolotrasamuel thanks!

@ithustle
Copy link

Hi. Using 9.1.0 version and still the same

@Richmond-Eribo
Copy link

same here, is there any solution yet?

@renatosantosti
Copy link

Tente:
!firebaseAdmin.apps.length ? firebaseAdmin.initializeApp() : firebaseAdmin.app();
ou
try{ firebaseAdmin.initializeApp() } catch(err){ firebaseAdmin.app() }

@markgoho
Copy link

markgoho commented Apr 2, 2021

here's what I'm doing:

const admin = require('firebase-admin');

if (admin.apps.length === 0) {
  admin.initializeApp();
}

@MisterCode415
Copy link

@markgoho that's the slam dunk right there ;D thank you.

@saydur961
Copy link

@markgoho Thank you so much

@arturjnt
Copy link

arturjnt commented Jul 27, 2021

Doesn't work for me unfortunately @markgoho
admin.apps.length is an [object Object]
So now it never gets in the if, and never initializes.

EDIT: I thought that was the problem, but actually I'm getting 1 app on the admin.apps array and that's why it doesn't enter the if.

// Init and signIn on Firebase
        console.log(`AAAAAAAAAAAAAAAAAAAA: ${admin.apps.length.toString()}`);
        if (admin.apps.length === 0) {
            admin.initializeApp({
                credential: admin.credential.cert(serviceAccount),
                databaseURL: 'https://****.firebaseio.com',
            });
        }

image

EDIT 2: Nevermind, I was initializing the app inside the exports.myFunction so it always only worked the first time.
Hope my "issue" helps someone doing the same mistake.

@cifuentesmx
Copy link

I guess It depends on how you are using the AdminSDK, what works for me (as I'm using as modules) is this.

const { initializeApp } = require('firebase-admin/app')
const { getAuth } = require('firebase-admin/auth')

if (!app) {
  const app = initializeApp()
  const auth = getAuth(app)
  module.exports = { auth }
}

@Applicafroguy
Copy link

Applicafroguy commented May 13, 2022

I have the same issue.

When I deploy firebase deploy --only functions --project staging

Error: Failed to load function definition from source: Failed to generate manifest from function source: Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

I am using firebase-tools: 10.9.2 , firebase-admin: 10.2.0 and firebase-functions: 3.21.1 I use firebase-functions/v1 and firebase-functions/v2,
I only get this error when I export v2 functions

// src/myfunc.ts
import * as f2 from 'firebase-functions/v2'

export const myfunc = f2.https.onRequest(async (request, response) => {
    response.send("Hello")
})
// src/index.ts
import { initializeApp } from 'firebase-admin/app'

initializeApp()

// export functions
export { myfunc } from './myfunc'

I have tried this and I still get the same error

// src/index.ts
let app

if (!app) {
  app = initializeApp()
}

EDIT: Found the issue it was caused by third-party imports

import fetch from 'node-fetch'

@andrewmclagan
Copy link

If your app is already created, you may need to delete it somewhere in your apps lifecycle before creating another. Firebase apps have global namespace. This will be specific to your setup:

For example in NestJS

  async onModuleInit() {
    const options = this.config.get<AppOptions>(FirebaseService.CONFIG_KEY);
    this.app = initializeApp(options);
  }

  async onModuleDestroy() {
    if (this.app) {
      await deleteApp(this.app);
    }
  }

@SwimmingPolar
Copy link

Checking the apps length looks suffice but it didn't work for me.
The below code seems redundant but at least worked for me.

let app: ReturnType<typeof initializeApp>

function getFireStore() {
  if (!app && !admin.apps.length) {
    try {
      app = initializeApp({
        credential: admin.credential.cert(configDecoded)
      })
    } catch (error) {
      console.error(error)
    }
  }

  return admin.firestore()
}

const firestore = getFireStore()

export const tokensCollection = firestore.collection('tokens')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests