Search code examples
reactjsfirebasegoogle-cloud-firestorefirebase-tools

React project has Firebase Emulator ApiKey Error


i have recently connected my React project to Firebase emulator. On the production environment, the app worked as it should but since moving to emulator, its unpredictable.

I get the following errors when I start the local emulator:

POST https://firebaseinstallations.googleapis.com/v1/projects/demo-project/installations 400

and

FirebaseError: Installations: Create Installation request failed with error "400 INVALID_ARGUMENT: API key not valid. Please pass a valid API key." (installations/request-failed).

Here is my code in my firebase.js file:

const firebaseConfig = {
  apiKey: process.env.REACT_APP_APIKEY,
  authDomain: process.env.REACT_APP_AUTHDOMAIN,
  projectId: process.env.REACT_APP_PROJECTID,
  storageBucket: process.env.REACT_APP_STORAGEBUCKET,
  messagingSenderId: process.env.REACT_APP_MESSAGINGSENDERID,
  appId: process.env.REACT_APP_APPID,
  measurementId: process.env.REACT_APP_MEASUREMENTID,
};

const hostname = window.location.hostname;
const app =
  hostname === "localhost"
    ? initializeApp({
        apiKey: "demo-key",
        authDomain: "demo-test",
        projectId: "demo-project",
        storageBucket: "default-bucket",
        appId: "demo-appId",
      })
    : initializeApp(firebaseConfig);

export let auth = getAuth(app);
export let db = getFirestore(app);
export const storage = getStorage(app);
export let functions = getFunctions(app);
export const analytics = getAnalytics(app);

if (hostname === "localhost") {
  connectAuthEmulator(auth, "http://localhost:9099");
  connectFirestoreEmulator(db, "localhost", 8080);
  connectStorageEmulator(storage, "localhost", 9199);
  connectFunctionsEmulator(functions, "localhost", 5001);
}

I have tried several configurations to resolve this error to no avail and without an apiKey, key/value pair, the local site doesn't render.

Any insights would be appreciated.


Solution

  • AFAICT "API key not valid" isn't thrown by the emulator, which leads me to believe you're calling production.

    A few things to check:

    • Ensure you're starting the emulators with demo-project like so:

    firebase emulators:start --project=demo-project

    • Make sure your browser's URL is actually "localhost" and not an explicit IP address, since window.location.hostname returns the host based on the browser URL

    • See if the getAnalytics call is causing the problem - there's no emulated Analytics service so this may be calling prod with "demo-project" and will necessarily fail.