Firebase Admin Failed to determine project ID



I have a react app and I have added firebase to it. The Sign Up creates a new user account but since the user has to be tracked I have gotten the user’s id token and added it to local storage. It then takes the user to a dashboard page with the route link “/dashboard” but anyone can go to that link without signing up, it takes the id token kept in local storage, it then uses firebase admin to verify the id. If the verification is a success, it loads the page. Else it redirects the user to the login page. However when I created a new account, I got directed to the dashboard, and then redirected back to the login page. The id token had been correctly put into the local storage and the account had been created, but I got the error
Failed to determine project ID: Error while making request: Failed to fetch. Error code: undefined at FirebaseAppError.FirebaseError [as constructor] (error.js:44) at FirebaseAppError.PrefixedFirebaseError [as constructor] (error.js:90) at new FirebaseAppError (error.js:125) at credential-internal.js:183.
Here is my code:
index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import firebase from "firebase/app";
import admin from "firebase-admin";

const firebaseConfig = {
  // In the actual code I have set all of them
}
firebase.initializeApp(firebaseConfig);
admin.initializeApp();

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);


Signup.js:

import React, { useState, useEffect } from "react";
import { useHistory, Link } from "react-router-dom";
import firebase from "firebase";
import admin from "firebase-admin";

function Signup() {
  const [userInfo, setUserInfo] = useState({email: "", username: "", password: ""});
  const [errorMessage, setErrorMessage] = useState();
  const [idToken, setIdToken] = useState();

  const history = useHistory();

  useEffect(() => {
    setIdToken(localStorage.getItem("idToken"));

    if (idToken !== undefined && idToken !== null) {
      admin.auth().verifyIdToken(idToken)
      .then(() => {
        history.push("/dashboard");
      })
      .catch(() => {
        localStorage.removeItem("idToken");
      })
    }
  }, []);

  const getText = ({target}) => {
    setUserInfo({...userInfo, [target.name]: target.value});
  }

  const signup = (e) => {
    e.preventDefault();

    const {username, email, password} = userInfo;

    if (username === "" || email === "" || password === "") {
      setErrorMessage("Username, Email and Password cannot be empty.");
    } else if (password.length < 8) {
      setErrorMessage("Password cannot be less than 8 characters long.");
    } else {
      firebase.auth().createUserWithEmailAndPassword(email, password)
      .then((userCredential) => {
        userCredential.user.updateProfile({
          displayName: username
        })
        userCredential.user.getIdToken()
        .then((idToken) => {
          localStorage.setItem("idToken", idToken);
          history.push("/dashboard");
        })
      })
      .catch((error) => {
        setErrorMessage(error.message);
      })
    }
  }

  return(
    <div>
      <form onSubmit={signup}>
        <input
          type="email"
          name="email"
          placeholder="Email"
          onChange={getText}
        />
        <br />
        <input
          type="text"
          name="username"
          placeholder="Username"
          onChange={getText}
        />
        <br />
        <input
          type="password"
          name="password"
          placeholder="Password"
          onChange={getText}
        />
        <br />
        <p>{errorMessage}</p>
        <input type="submit" value="Sign Up" />
        <p>Already have an account? <Link to="/login">Log In</Link></p>
      </form>
    </div>
  );
}

export default Signup;


Dashboard.js:

import React, { useEffect } from "react";
import { useHistory } from "react-router-dom";
import admin from "firebase-admin";

function Dashboard() {
  const history = useHistory();

  useEffect(() => {
    const idToken = localStorage.getItem("idToken");

    if (idToken !== undefined && idToken !== null) {
      admin.auth().verifyIdToken(idToken)
      .catch((error) => {
        console.log(error);
        localStorage.removeItem("idToken");
        history.push("/login");
      })
    } else {
      localStorage.removeItem("idToken");
      history.push("/login");
    }
  }, []);
  
  return <h1>Dashboard</h1>
}

export default Dashboard;

Answer

Firebase-admin example initialization (it’s different from firebase client side)

let admin = require('firebase-admin')
let serviceAccount = require('./theserviceaccountfile.json');

let db

module.exports = async function() {

        if (!admin.apps.length) {
            admin.initializeApp({
               credential: admin.credential.cert(serviceAccount),
               databaseURL: "https://project-id.firebaseio.com",
             })
             if (!db) {
                db = admin.database()
             }
        }
        return db
    
    }


Source: stackoverflow