Write beautiful Node.js APIs using async/await and Firebase

Write beautiful Node.js APIs using async/await and Firebase

Write beautiful Node.js APIs using async/await and Firebase, This tutorial will cover the typical use cases you’ll come across when writing RESTful API endpoints to read and write to a Firebase Database instance.

There will be a focus on beautiful asynchronous code, which makes use of the async/await feature in Node.js (available in v7.6 and above).

(Feel free to smile sweetly as you wave goodbye to callback hell

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.

Writing data

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

// 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);
});

firebase-write.js

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:

// 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);
    }
  };
});

firebase-write-error-handling.js

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.”

Note: if some of the ES2015+ syntax looks unfamiliar to you, check out the Babel ES2015 guide.### Reading data

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:

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

firebase-read-promise.js

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

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

firebase-read.js

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:

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

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

promise-chain.js

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:

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();

promise-chain-async.js

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:

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();

promise-chain-async-error-handling.js

Parallel async/await requests

What about cases where you need to fetch multiple records from your Firebase Database at the same time?

Easy. Just use the Promise.all() method to run Firebase Database requests in parallel:

// API
router.get('/words', async (req, res) => {
  const wordsRef = db.ref(`words`).once('value');
  const usersRef = db.ref(`users`).once('value');
  const values = await Promise.all([wordsRef, usersRef]);
  const wordsVal = values[0].val();
  const userVal = values[1].val();
  res.sendStatus(200);
});

parallel-async-await.js

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:

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

client-read.js

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:

// 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);
});

firebase-snapshot.js

Thanks for reading!

Recommended Courses:

Supreme NodeJS Course - For Beginners

Learn Web Scraping with NodeJs in 2019 - The Crash Course

NodeJS & MEAN Stack - for Beginners - In Easy way!

End-to-End with Ionic4 & Parse/MongoDB on NodeJS/Express

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Difference between AngularJS, React, Ember, Backbone, and Node.js.

The most common thing between all of them is that they are Single Page Apps. The SPA is a single page where much of the information remains the same and only some piece of data gets modified when you click on other categories/option.

Node.js Tutorial for Beginners | Node.js Crash Course | Node.js Certification Training

This courseis designed for professionals who aspire to be application developers and gain expertise in building real-time, highly-scalable applications in Node.js. The following professionals can go for this course :

Why learn Node.js?

Node.js uses JavaScript - a language known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Using Node.js you can build simple Command Line programs or complex enterprise level web applications with equal ease. Node.js is an event-driven, server-side, asynchronous development platform with lightning speed execution. Node.js helps you to code the most complex functionalities in just a few lines of code...

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Docker for Node.js Projects From a Docker Captain

Intro To MySQL With Node.js - Learn To Use MySQL with Node!

Node.js Absolute Beginners Guide - Learn Node From Scratch

React Node FullStack - Social Network from Scratch to Deploy

Selenium WebDriver - JavaScript nodeJS webdriver IO & more!

Complete Next.js with React & Node - Beautiful Portfolio App

Build a Blockchain & Cryptocurrency | Full-Stack Edition