1

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.

enricw
  • 263
  • 4
  • 19
  • What do you mean by "created automatically"? Can you share your complete code related to this so we can see how you are intiializing Firebase and using it? – Dharmaraj Jan 14 '23 at 14:06
  • Hi, I've now uploaded the relevant code. By 'created automatically' I mean it was created by using the firebase commands in the command line. – enricw Jan 14 '23 at 15:41
  • 1
    I believe you're mixing code from Firebase v9 and V8, you should follow one of both. For instance: You're importing `initializeApp` which is a firebase v9 function and so in this case app should be declared like this: `app = initializeApp(firebaseConfig)`. There are similar problems with respect to db as well. Here is a proper guide to working with firebase v9: [Firebase](https://youtube.com/playlist?list=PL4cUxeGkcC9jERUGvbudErNCeSZHWUVlb) – Shahzaib Jan 16 '23 at 12:18

2 Answers2

2

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thankyou! This is probably an error I would have gotten after solving this. My question still remains: Am I accessing the "public" directory of my app and the destination of the file wrong? Is the best solution to copy all html code from MY_APP/index.html to MY_APP/src/dist/index.html? – enricw Jan 14 '23 at 19:52
  • Please don't remove a problem from your question that I already addressed in my answered. I answered why you get the "Uncaught ReferenceError: db is not defined" that you had in your question, but now that you removed that from the question my answer is like a dangling pointer and not useful for future visitors. :-/ If I addressed a problem in your question that was not what you were looking for, consider whether tis shouldn't have been two separate posts to begin with. – Frank van Puffelen Jan 14 '23 at 20:09
  • What? I think you are confused... I haven't removed anything from my post. – enricw Jan 14 '23 at 21:39
  • Woops, you're right. I overlooked the error "db is not defined" in the post, so thought you had removed it. --- The part about `public` seems to be about Firebase Hosting, which is completely separate though - so the same recommendation would apply: isolate the problem to a single Firebase product, so that we can answer for just that one. I answered why you get the error message accessing Firestore that you have in your question, while you seem more interested in how to point Firebase Hosting to a specific directory. --- Paths in `firebase.json` are relative to where that file is on your disk. – Frank van Puffelen Jan 14 '23 at 22:21
  • So to initialize the constant db, I should write: const db= 0; or var db; and then db = firebase.firestore(); When I run the app with either of these changes, I still get the "Uncaught ReferenceError: db is not defined". – enricw Jan 15 '23 at 08:12
1

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');
});
Kitanga Nday
  • 3,517
  • 2
  • 17
  • 29
  • 1
    Thank you. Would you put the code as a standalone function in the javascript file? or in the html file within a – enricw Jan 21 '23 at 16:30
  • 1
    Put it in a file. And other important functions as well. Look into Vite, you can't be coding the way you are right now, it's not modern. Importing, tree shaking, these are things you should be looking into, but if you are only trying to learn firebase, then the way you have it isn't too bad. – Kitanga Nday Jan 21 '23 at 17:02
  • @enricw Your last question is a little confusing. What are you trying to create, a blogging system using firestore? Or a tool to create posts using firestore? – Kitanga Nday Jan 21 '23 at 17:04
  • I'm trying to send the time type data inputted by users to my firestore database, using the event function at the end of my index.html file. I believe the method used is deprecated, but can't find how it is used nowadays. Thanks again. – enricw Jan 21 '23 at 17:31
  • @enricw Ah I see, you are supposed to use `hora.value` and not just `hora` since `hora` is a reference to a dom element and not the value the user selected. – Kitanga Nday Jan 21 '23 at 17:36
  • 1
    @enricw I just tested it, use `.set({ Hora: hora.value })` – Kitanga Nday Jan 21 '23 at 17:40
  • 1
    Corrected, thanks. Do you not get "TypeError: db.collection is not a function" message? – enricw Jan 21 '23 at 17:42
  • 1
    @enricw I don't know what your file structure is or what could be causing that. Look at the error. There's a little arrow on the left. Click on it, it should show you what function lead to that error. – Kitanga Nday Jan 21 '23 at 17:45