'Firebase: Error (auth/invalid-api-key) with demo project

I am trying to write some automated tests with the Firebase client sdk. These tests are supposed to use the Firebase Auth Emulator. In order to avoid screwing up production data, I am using the emulators with a demo project id (as described in the documentation).

I start the emulator with this command:

firebase emulators:start --project demo-test --only functions,firestore,storage,auth

Then in my tests, I initialize the app with:

import { initializeApp } from 'firebase/app'
import { getAuth, connectAuthEmulator } from 'firebase/auth'

const app = initializeApp({ projectId: 'demo-test' })
const auth = getAuth(app)
connectAuthEmulator(auth, 'http://localhost:9099')

When the test initializes, I get this error:

 FirebaseError: Firebase: Error (auth/invalid-api-key).

    > 45 |     const auth = getAuth(app)
         |                  ^

Note: This problem only occurs with authentication. I can successfully connect to other emulators like Firestore.

It seems that despite what the documentation says, I can't actually connect the client SDK to a demo project and use the auth emulator. Every time I try, it throws this error.

Does someone know how to set up a demo project emulator and connect the client sdk to the auth emulator?



Solution 1:[1]

I've got this running by using production apiKey and authDomain.

const app = initializeApp({
  projectId: 'demo-test',
  apiKey: '...',
  authDomain: '...',
});

But obviously this isn't ideal considering demo projects shouldn't have any apiKey and authDomain.

Also, I was worried when the warning "Running in emulator mode. Do not use with production credentials" shows, while I use the production apiKey. But turns out the warning means we shouldn't input any sensitive information (such as real passwords) when running the emulator, as stated here. So I think we have no problem for using production apiKey to connect to the emulator.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1