"firebase.database.ref is not a function" when connecting to Firebase using JS
Solution 1
You have to do
const db = firebase.database().ref();
See https://firebase.google.com/docs/database/web/start and https://firebase.google.com/docs/reference/js/firebase.database.Database
Note that you could maybe rename your variable to rootRef
instead of db
, and use db
for firebase.database()
Solution 2
I am not sure if i can be of much use without seeing the entire code , (not talking about the firebase apikeys and stuff) but i came accross this issue couple of weeks back while i was working with React-Native . Now though they dont function the same way the error might be because you are missing few libraries or you are not using the latest versions of them . The error details are not as friendly as they seem . I fixed this issue with installing the latest libraries - headsup sometimes even when u do install them they tend to install with errors so best guess is to "delete the installed packges first" and then"reinistall" . Also add the following
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-auth.js"></script>.
After that , i remember i had to sometimes Database and Auth pieces need to be required separately since they aren't bundled when including Firebase in this way.So i fixed it usng a the below code ,
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
Last but not least you are also missing the function () in your code , but im not sure f that alone is the issue . so just add
const db = firebase.database().ref();
.
I do have a feeling this could fix it alone , but sometimes it might need all the packages above as well . Let me know how it goes . Good luck . Connecting can be a hasle sometimes for all not just you.
user10431501
Updated on June 12, 2022Comments
-
user10431501 almost 2 years
I am getting a weird error when trying to connect a web page to firebase realtime database. I get the error,
Uncaught TypeError: firebase.database.ref is not a function.
The error points to the below line of code
const db = firebase.database.ref();
I copied the script from my firebase project and I added the imports. For the initialisation I have removed the apiKey etc for the question.
<script src="https://www.gstatic.com/firebasejs/5.10.0/firebase-app.js"> </script> <script src="https://www.gstatic.com/firebasejs/5.10.0/firebase- database.js"></script> <script> // Initialize Firebase const config = { apiKey: "", authDomain: "", databaseURL: "", projectId: "", storageBucket: "", messagingSenderId: "" }; firebase.initializeApp(config); </script> <script> const db = firebase.database.ref(); </script>