How to use Firebase Realtime Database in a Node.js app
Tags: node, javascript, database, tutorial
Published: 2020-11-24 11:33:17

### **What is Firebase Realtime Database?**
It is a NoSQL database by [Google](https://firebase.google.com) that lets you store and access data in realtime.
Note:
> All Firebase Realtime Database data is stored as JSON objects.

### **What is REPL, CLI and Node.js?**
[Click here](https://dev.to/irohitgaur/making-a-cli-app-in-repl-with-persistent-data-using-node-js-4bpo) to check out the blog post where I have explained them in detail.

### **Steps to perform on Firebase**
1. Sign in to your Google account, go to [Firebase console](https://console.firebase.google.com) and click on **`Add Project`**

2. Give a name to your project, uncheck "Enable Google Analytics for this project" if you do not wish to enable analytics for the project and click on continue to create the project.

3. Select Web on the Project dashboard:
![Web app - firebase](https://dev-to-uploads.s3.amazonaws.com/i/wbtaw81saj7bs71qq8z0.png)

4. Give a name to your app, then click on "Register app"
![web app name - firebase](https://dev-to-uploads.s3.amazonaws.com/i/qlwb43x3bufa3zfl0mw6.png)

5. That will generate your app's Firebase configuration which we will need in our project. Copy it for later use.
![Firebase config](https://dev-to-uploads.s3.amazonaws.com/i/rmb4tds3q0rscny4myh4.png)

6. Proceed to the console, select "Realtime Database" and click "Create Database"

7. Select "Start in test mode" and click "Enable".
[Read](https://firebase.google.com/docs/database/security/get-started?authuser=0) the security rules of realtime database and secure your app accordingly. For the purpose of this tutorial, we will just go ahead with test mode.

### **Steps to implement Firebase in your app**

1. Include firebase package in your Node.js app
```javascript
var firebase = require('firebase')
```

2. Paste the Firebase configuration that you copied earlier. I have shown an empty config for your reference here:
```javascript
var firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: ""
}
```

3. Initialize your Firebase app:
```javascript
firebase.initializeApp(firebaseConfig)
```

4. Get a reference to the database service:
```javascript
let database = firebase.database()
```

Firebase is now configured with our app.

### **How to write data to firebase?**
Create a reference to your custom path at which you want to write your JSON object (mentioned as "obj" in the snippet below).
Then you set that object on the path:
```javascript
database.ref("customPath").set(obj, function(error) {
    if (error) {
      // The write failed...
      console.log("Failed with error: " + error)
    } else {
      // The write was successful...
      console.log("success")
    }
})
```

### **How to read data from firebase?**
Create a reference to your custom path at which the data was written. Then you read the value at that path:
```javascript
database.ref('customPath').once('value')
.then(function(snapshot) {
    console.log( snapshot.val() )
})
```

You can either read the data once or continously read the data at a path and listen for changes. For more details, check out their [documentation](https://firebase.google.com/docs/database/web/read-and-write?authuser=0)

### **You can check out this CLI app I made which tests your knowledge on Harry Potter series and keeps track of your highscore:**
* [Click here to play](https://repl.it/@iRohitGaur/2-Are-You-A-Potterhead?embed=1&output=1)
* [Click here to check out the code](https://github.com/iRohitGaur/2-Are-You-A-Potterhead)

#### **If you have any queries, get in touch with me on [Twitter](https://twitter.com/iRohitGaur)**