Connecting Realtime Database to Firebase Function

1. Introduction

In this post, we are going to build a Firebase Function that connects to a Realtime Database.

2. Setting Up Firebase Environment

To start developing cloud function, first, we need a firebase project. You can quickly create a new project by using Firebase Console.

2.1. Creating a Realtime Database

After creating a new project, now, we need to set up a new database.

Let’s start with Real-time database under Database section. You will find a root key containing a null value.

Click on Add button visible under root element. Let’s enter following key-value pair:

connection: true

We added a new element to the database. This element will be fetched from our cloud function, created in next section.

2.2. Setting up Firebase SDK

To develop function, first, we need to setup Firebase SDK on our system. You can follow the documentation setup Firebase SDK, if not already done.

3. Connecting Firebase Function to Database

First, we need to import firebase-admin module.

const admin = require("firebase-admin");

Next, initialize admin app instance.

admin.initializeApp(functions.config().firebase);

Finally, we need to connect database.

var db = admin.database();
var ref = db.ref("/connection");

Now our function is ready to fetch data from the database.

ref.once("value", function(snapshot) {
 value = snapshot.val();
}

Complete executable function:

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.dbconnection = functions.https.onRequest((request, response) => {
  var db = admin.database();
  var ref = db.ref("/connection");
  console.log('database ref url: ' + ref);
  ref.once("value", function(snapshot) {
    console.log("key:" + snapshot.key + ", value: " + snapshot.val());
  });
  response.send("Function successfully executed!");
});

You just need to copy this function to your index.js. That’s it. Now deploy it under firebase functions.

Firebase command will return a Function URL. This URL is unique and dependent on the project. In my case:

https://us-central1-cloudtechpro-blog.cloudfunctions.net/dbconnection

Run the Function URL in any browser. Now go to function logs, and you will find:

key: connection, value: true

Now you can further edit this function to meet your requirements.

4. Conclusion

In this tutorial, we learned how to connect Firebase Realtime database from Cloud Function.

Leave a Reply

Your email address will not be published. Required fields are marked *