Andrew Lee
Andrew Lee

Reputation: 304

Having trouble connecting to my Firebase database - Node & Express

I am still learning programming in general so sorry if I don't make sense.

I am trying to connect to my firebase database but I get a PERMISSION_DENIED error. The database in my firebase is set to Test mode so anyone should be able to access it.

I have added all the npm packages needed based on the firebase docs as well.

Let me know if I need to provide more information.

I am not sure what I am doing wrong here. Would anyone know? Any help is appreciated.

Here is my module file

var express = require('express');
var firebase = require('firebase');

// Initialize Firebase
var config = {
  apiKey: "apikey",
  authDomain: "authdomain",
  databaseURL: "databaseurl",
  storageBucket: "storagebucket"
};

firebase.initializeApp(config);

var db = firebase.database();
var ref = db.ref("/users");

ref.on("value", function(snapshot) {
  console.log(snapshot.val());
}, function (errorObject) {
  console.log("The read failed: " + errorObject.code);
});


var index = require('./routes/index');
app.use('/', index);

module.exports = app;

Here is my routes/index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'The Title' });
});

module.exports = router;

Upvotes: 2

Views: 983

Answers (2)

Andrew Lee
Andrew Lee

Reputation: 304

So I figured out a way to properly connect to my firebase database. I am not sure if this is the best way but the first thing I did was delete the current database and recreated it (not sure if this helped or was needed but I just wanted a fresh install just in-case something was wrong before.)

Then inside my database dashboard in firebase I went to the "Gear Icon => Project Settings" next to "Project Overview" header on the upper left of the dashboard screen. From here under Firebase Admin SDK I clicked "Generate New Private Key" button on the bottom.

This gave me a .json file which was downloaded onto my computer. I changed the downloaded files name to something more simple like myfirstapp-firebase-db.json. I added this file into the folder where my node js is being stored.

Before I started writing the code to connect to my firebase database, I had to make sure that my "Database => Rules" were set to true for read & write privileges in my firebase project.

Database Rules setup:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

After everything needed to configure firebase was taken care of, I simply configured my module.js file to properly connect. Below is the code necessary to connect to firebase. The two important things were "serviceAccount" and "databaseURL".....

var firebase = require('firebase');

// Initialize firebase
firebase.initializeApp({
  serviceAccount: "./<your-service-account-url>-firebase-db.json",
  databaseURL: "https://<your-database-url>.firebaseio.com/"
});

var db = firebase.database();
var ref = db.ref("/users");

..... The "serviceAccount" is a route to the .json file downloaded from the step "Generate New Private Key" above. You can find the databaseURL inside the "Database" dashboard on the top of the white block inside firebase. I simply copied and pasted that url into the databaseURL.

Then I put firebase.database() into a var = db and then specified the ref.

At this point my connection was successful and when I did a node modules.js it showed me in the console everything that is in the ref database. Make sure to have some pre populated fields in the database for the console to show you all the items inside. I hope this may be helpful to someone and if anyone knows of a better way of doing this I would love to know your suggestions!

Upvotes: 1

Justin Walton
Justin Walton

Reputation: 31

Asynchronous listeners: Data stored in a Firebase Realtime Database is retrieved by attaching an asynchronous listener to a database reference. The listener is triggered once for the initial state of the data and again anytime the data changes. An event listener may receive several different types of events.

Helpful link https://firebase.google.com/docs/database/admin/retrieve-data

You need to create a reference variable that corresponds to your database path

var ref = db.ref("server/saving-data/fireblog/posts");

and then you'll attach an asynchronous callback to read the data at the reference

    ref.on("value", function(snapshot) {
      console.log(snapshot.val());
    }, function (errorObject) {
      console.log("The read failed: " + errorObject.code);
    });

I believe your issue with PERMISSION_DENIED is that you're using

var db = firebase.database();

instead of

var db = admin.database();

Upvotes: 2

Related Questions