Search code examples
reactjsfirebase-authenticationenvironment-variablescreate-react-appapi-key

How to solve "Firebase: Error (auth/invalid-api-key)" error in Reactjs?


I have a very frustrating error involving the use of API key with Firebase Authentication.

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

I'm using environment variables to avoid from hardcoding my API key into my config files.

Tried a lot of things: making sure I copied the API keys correctly, restarting my dev server, verifying identity using the firebase-admin npm module etc. etc.

./src/config/firebase.js

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";

const app = firebase.initializeApp({
  apiKey: process.env.QUIZZI_FIREBASE_API_KEY,
  authDomain: process.env.QUIZZI_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.QUIZZI_FIREBASE_PROJECT_ID,
  storageBucket: process.env.QUIZZI_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.QUIZZI_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.QUIZZI_FIREBASE_APP_ID
});

export const auth = app.auth();
export const database = firebase.firestore();
export default app;

.env.local

QUIZZI_FIREBASE_API_KEY=xxx
QUIZZI_FIREBASE_AUTH_DOMAIN=xxx
QUIZZI_FIREBASE_DATABASE_URL=xxx
QUIZZI_FIREBASE_PROJECT_ID=xxx
QUIZZI_FIREBASE_STORAGE_BUCKET=xxx
QUIZZI_FIREBASE_MESSAGING_SENDER_ID=xxx
QUIZZI_FIREBASE_APP_ID=xxx

I also referred to this thread but none of the solutions are working for me.

How do I get rid of this error?


Solution

  • After digging through the thread mentioned deeper, I found out it was because of the naming convention for create-react-app for environment variables.

    I'm supposed to use REACT_APP_* to name any env variables for security reasons.

    Credit to this article.

    Refer to the official docs for more details.