Skip to main content

Using async/await and the Firebase Database to Write Beautiful Node.js APIs

00:04:33:89

This tutorial is all about writing elegant and effective RESTful APIs for reading and writing data to a Firebase Database using async/await in Node.js. Async/await (available in Node.js v7.6 and above) is a game-changing feature that makes it much easier to write asynchronous code and say goodbye to callback hell. We'll be covering the common use cases you're likely to encounter when working with the Firebase Database, and we'll focus on writing beautiful, easy-to-follow code that makes the most of async/await. Whether you're new to building APIs or an experienced developer, this tutorial has something to offer.

Data Codes through Eyeglasses

Prerequisites

I’ll assume that you already have a Node.js application set up with the Firebase Admin SDK. If not, then check out the official setup guide. You’ll also need to have Node.js v7.6 or above installed on your machine.

Writing data to the Firebase Database

First off, let’s create an example POST endpoint which will save words to our Firebase Database instance:

js
// Dependencies
const admin = require('firebase-admin');
const express = require('express');

// Setup
const db = admin.database();
const router = express.Router();

// Middleware
router.use(bodyParser.json());

// API
router.post('/words', (req, res) => {
  const {userId, word} = req.body;
  db.ref(`words/${userId}`).push({word});
  res.sendStatus(201);
});

This is a very basic endpoint which takes a userId and a word value, then saves the given word to a words collection. Simple enough.

But something’s wrong. We’re missing error handling! In the example above, we return a 201 status code (meaning the resource was created), even if the word wasn’t properly saved to our Firebase Database instance.

So, let’s add some error handling:

js
// API
router.post('/words', (req, res) => {
  const {userId, word} = req.body;
  db.ref(`words/${userId}`).push({word}, error => {
    if (error) {
      res.sendStatus(500);
      // Log error to external service, e.g. Sentry
    } else {
      res.sendStatus(201);
    }
  });
});

Now that the endpoint returns accurate status codes, the client can display a relevant message to the user. For example, “Word saved successfully.” Or “Unable to save word, click here to try again.”

Reading data from the Firebase Database

OK, now that we’ve written some data to our Firebase Database, let’s try reading from it.

First, let’s see what a GET endpoint looks like using the original promise-based method:

js
// API
router.get('/words', (req, res) => {
  const {userId} = req.query;
  db.ref(`words/${userId}`).once('value')
    .then( snapshot => {
      res.send(snapshot.val());
    });
});

Again, simple enough. Now let’s compare it with an async/await version of the same code:

js
// API
router.get('/words', async (req, res) => {
  const {userId} = req.query;
  const snapshot = await db.ref(`words/${userId}`).once('value');
  res.send(snapshot.val());
});

Note the async keyword added before the function parameters (req, res) and the await keyword which now precedes the db.ref() statement.

The db.ref() method returns a promise, which means we can use the await keyword to “pause” execution of the script. (The await keyword can be used with any promise).

The final res.send() method will only run after the db.ref() promise is fulfilled.

That’s all well and good, but the true beauty of async/await becomes apparent when you need to chain multiple asynchronous requests.

Let’s say you had to run a number of asynchronous functions sequentially:

js
const example = require('example-library');

example.firstAsyncRequest()
  .then( fistResponse => {
    example.secondAsyncRequest(fistResponse)
      .then( secondResponse => {
        example.thirdAsyncRequest(secondResponse)
          .then( thirdAsyncResponse => {
            // Insanity continues
          });
      });
  });

This is a very common pattern in Node.js, but it’s not very readable. It’s also very easy to make a mistake and end up with a callback hell. Not pretty. This is also known as the “pyramid of doom” (and we haven’t even added error handlers yet).

Now take a look at the above snippet rewritten to use async/await:

js
const example = require('example-library');

const runDemo = async () => {
  const fistResponse = await example.firstAsyncRequest();
  const secondResponse = await example.secondAsyncRequest(fistResponse);
  const thirdAsyncRequest = await example.thirdAsyncRequest(secondResponse);
};

runDemo();

The code is much easier to read and understand. It’s also much easier to add error handling and other logic.

No more pyramid of doom! What’s more, all of the await statements can be wrapped in a single try/catch block to handle any errors:

js
const example = require('example-library');

const runDemo = async () => {
  try {
    const fistResponse = await example.firstAsyncRequest();
    const secondResponse = await example.secondAsyncRequest(fistResponse);
    const thirdAsyncRequest = await example.thirdAsyncRequest(secondResponse);
  }
  catch (error) {
    // Handle error
  }
};

runDemo();

One more thing

When creating an endpoint to return data retrieved from a Firebase Database instance, be careful not to simply return the entire snapshot.val(). This can cause an issue with JSON parsing on the client.

For example, say your client has the following code:

js
fetch('https://your-domain.com/api/words')
  .then( response => response.json())
  .then( json => {
    // Handle data
  })
  .catch( error => {
    // Error handling
  });

The snapshot.val() returned by Firebase can either be a JSON object, or null if no record exists. If null is returned, the response.json() in the above snippet will throw an error, as it’s attempting to parse a non-object type.

To protect yourself from this, you can use Object.assign() to always return an object to the client:

js
// API
router.get('/words', async (req, res) => {
  const {userId} = req.query;
  const wordsSnapshot = await db.ref(`words/${userId}`).once('value');

  // BAD
  res.send(wordsSnapshot.val())

  // GOOD
  const response = Object.assign({}, snapshot.val());
  res.send(response);
});

In case you want to read more about Startups, Firebase, and Tech in general, feel free to follow me on my social channels: Instagram, Twitter, and LinkedIn.