# FirebaseApp Client in Scala

While I was using the `FirebaseAuth` Java client, I was getting this error:

`Execution exception[[IllegalStateException: FirebaseApp name [DEFAULT] already exists!]]`

When my Play application reloaded itself, `FirebaseApp.initializeApp()` was getting called again from the application loader, which caused this error.

I made a simple wrapper to handle this:

```scala
import com.google.auth.oauth2.GoogleCredentials
import com.google.firebase.{ FirebaseOptions, FirebaseApp }

import scala.util.Try

object FirebaseAppLoader {
  def apply(credentials: GoogleCredentials): FirebaseApp = {
    Try(FirebaseApp.getInstance()).toEither match {
      // App hasn't been initialized yet, so we initialize it
      case Left(_: IllegalStateException) =>
        FirebaseApp.initializeApp(
          new FirebaseOptions.Builder()
            .setCredentials(credentials)
            .build
        )
      // Reuse the already-initialized app
      case Right(app) => app
      // Some other exception occurred
      case Left(e) => throw e
    }
  }
}
```

We simply just try to get the Firebase app instance (wrapped in a `Try`), and if it doesn't exist, we initialize it, which should happen just once.

Using this wrapper is as simple as `val firebaseApp: FirebaseApp = FirebaseAppLoader(credentials)`. Or with macwire, `val firebaseApp: FirebaseApp = wireWith(FirebaseAppLoader(_))`.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.alanqthomas.io/scala/firebaseapp-client-in-scala.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
