skip to Main Content

I am trying (and failing) to implement Firebase on my existing web-app.
I keep getting the error: Uncaught FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created

I believe that the problem resides with my file structure. In /MY_APP, I have the files I created and wrote for my app. In inner directories, there are the firebase automatically created .html and .js files.

|- /MY_APP
    |- index.html <-- contains my web-app
    |- code.js
    |- styles.css
    |- /src
        |- index.js <-- contains initializeApp Firebase config (apiKey, ...)
        |- /dist
            |- firebase.json
            |- .firebaserc.json
            |- /ManresaSegura
                |- index.html <-- example Firebase app (created automatically)
                |- app.js
 

Desired result: Continue using my original "index.html" file (the one found inside /MY_APP directory)

firebase.json (as created by firebase):

    {
  "hosting": {
    "public": "ManresaSegura",  
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "database": {
    "rules": "database.rules.json"
  }
}

I tried changing the following (which didn’t work):

"public": "../../../MY_APP"
...
"destination": "../../index.html

*EDIT: Additional code, as asked for:

index.js (Firebase initialization)

import {initializeApp} from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js';
    
    //import {initializeApp} from 'firebase/app';
    //import { getAuth, onAuthStateChanged } from 'firebase/auth';
    
    
    const firebaseApp = initializeApp({
        apiKey: "XXXXXX",
        authDomain: "XXXXXXX",
        projectId: "XXXXXXXXXXXX",
        storageBucket: "XXXXXXXXXXX",
        messagingSenderId: "XXXXXXXXX",
        appId: "XXXXXXXXXXXXXXX",
        measurementId: "XXXXXXXXX"
        
    });
    
    
    const auth = getAuth(firebaseApp);

app.js (db is defined, which is then instanced in index.html)

document.addEventListener("DOMContentLoaded", event => {

    const app = firebase.app();
    
    const db = firebase.firestore();
    
    const myPost = db.collection('posts').doc('firstpost');

 });

index.html (original)

<html>
    <head>

        ...
        <script type="text/javascript" src="code.js"></script>

        <!-- Firebase -->

        <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>  
        <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"></script> 

        

    <script type="module" defer src="src/index.js?useEmulator=true"></script>
        <!-- update the version number as needed -->
    <script defer src="/__/../node_modules/firebase/firebase-app-compat.js"></script>
    <!-- include only the Firebase features as you need -->
    <script defer src="/__/../node_modules/firebase/firebase-auth-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-database-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-firestore-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-functions-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-messaging-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-storage-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-analytics-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-remote-config-compat.js"></script>
    <script defer src="/__/../node_modules/firebase/firebase-performance-compat.js"></script>
    <!-- 
      initialize the SDK after all desired features are loaded, set useEmulator to false
      to avoid connecting the SDK to running emulators.
        -->
    

    </head>
    
    <body id="caixaCos">
       <script src="src/dist/ManresaSegura/app.js">  
            
        </script>

        ...
        <!-- Input type data I want to send to firebase database -->
        <input class="input-time" type="time" id="appt" name="appt"
        min="09:00" max="18:00" required>
        

        <button id="boto-zonaInsegura" type="submit">
                Enviar
        </button>

                <script type="text/javascript">
                
                document.getElementById("boto-zonaInsegura").onclick = function () {
                    const hora = document.querySelector(".input-time");  
                    db.collection("contact-form")
                    .doc()
                    .set({
                        Hora: hora,
                    })
                };

            </script> 

        </div>
...
        
    </body>
</html>

As firebase isn’t correctly implemented, I get the error Uncaught ReferenceError: db is not defined

Question: What am I doing wrong in the firebase.json file, why doesn’t it access the my app?
Is the only neat way of proceeding to copy all my code into the index.html created by firebase (in the /ManresaSegura directory)?

Thanks a lot. I am a novice in Firebase and not very skilled in js.

2

Answers


  1. That last code snippet (index.html) in your question doesn’t define db anywhere, but does then try to use db to access Firestore, which leads to the error message.

    If you want to use Firestore in your index.html too, you’ll need to ensure that you initialize Firebase and your db variable are initialized before that block executes.

    It’s actually fairly uncommon to have script blocks in your index.html when you also have dedicated files like code.js and app.js, so I recommend moving all JavaScript code into those files – at which point they’ll be executed after the initialization has completed.

    Login or Signup to reply.
  2. db is initialised in an event’s callback. Which means it isn’t available outside the scope of that callback. What you want to do is this

    let app;
    let db;
    
    document.addEventListener("DOMContentLoaded", event => {
    
        app = firebase.app();
    
        db = firebase.firestore();
    
        const myPost = db.collection('posts').doc('firstpost');
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search