šŸš€ How to rapidly develop and deploy a Node.js microservice to enhance the capabilities of React and Firebase

Sven Adlung
Ć¼berdosis
Published in
7 min readJan 15, 2018

In times of JavaScript-based frontend applications driven by frameworks like React and cloud-hosted databases like Firebase in the backend, some functions (usually done on a server) are lacking quickly, once the application breaks out of bounds. There are situations where you want to extend the backend capabilities: use cronjobs or send e-mails without doing that by triggering external webservices from the client-side-code and probably share secret API keys with the world.

Whatā€™s missing is an easy and rapid way to develop and deploy simple microservices that are built as a layer between frontend app and cloud-based backend.

Since 2017, there is an open Beta for Firebase Cloud Functions which is reliable just for these challenges. Unfortunately, some things are only available when switching to the Blaze plan (for example perform HTTP requests to external services from a Cloud Function). Letā€™s find another way.

A common way would be to create a small PHP application with a framework like Laravel ( šŸ’œ ) or even smaller with Lumen i.e. Or just use Vanilla PHP. The next step is getting a server to run on this project. Why not put everything into a docker container ā€¦ and anyways, what about the deployment? Letā€™s set up a Jenkins deployment to get everything automated.

ā° ā° ā° ā° ā° ā° ā°

Phew! You see, things become huge fast! Donā€™t get me wrong ā€” usually thatā€™s the way I would probably go. But sometimes itā€™s just too much...

Node.js microservice in the middle

Depending on the case, Node.js might be enough to fulfil the backend needs. And anyways, you are using JavaScript in the frontend, why not stick with it in the backend?

This article wonā€™t dig into details, the advantages or disadvantages of
Node.js ā€” it will just give you a few small examples for our previous points concerning React and Firebase.

Start with a clean Node.js project

Create a new folder (mkdir example-app), jump into it (cd example-app) and create a new project (yarn init). Just follow the points and enter your preferences:

$ yarn init
yarn init v0.27.5
question name (example-app):
question version (1.0.0):
question description:
question entry point (index.js):
question repository url:
question author:
question license (MIT):
success Saved package.json
Done in 8.91s.

I prefer adding express to communicate with the app (yarn add express). Next we create a server.js (touch server.js). This will be our entry point.

Add some boilerplate code to get everything running:

Thatā€™s pretty much it šŸŽ‰. Start it with yarn start and open localhost:3000 in your browser.

Interact with Firebase (Firebase Admin SDK)

To get and set data from firebase, you just need to add the firebase-admin package (yarn add firebase-admin).

To connect to firebase, you need to get a so called service account key. When doing so, just follow the instructions given by the firebase docs:

  1. Navigate to the Service Accounts tab in your projectā€™s settings page.
  2. Select your Firebase project. [ā€¦]
  3. Click the Generate New Private Key button at the bottom of the Firebase Admin SDK section of the Service Accounts tab.

Letā€™s add everything to our server.js.

As you can see I am using some environment variables. More about this later ...

With this done, you can connect to your Firebase database and do several things, even things you canā€™t achieve in the Firebase Console itself. In our case we needed to retrieve some user informations (by a given user uid) and process them.

Whatā€™s next? Well, we also needed to do some same action periodically every night. Letā€™s add a cronjob for that.

Automate tasks with cron

This is done easily with the node-cron package. So run yarn add node-cron and implement it to the code:

What else could be useful? Maybe send an e-mail (to a given user at a specific time ā€¦ šŸ™ƒ)!

Send an e-mail through an external SMTP service with Node.js

Here we use a package called nodemailer (yarn add nodemailer):

Just combine everything and you can do things you usually canā€™t do with React and Firebase alone (except using firebase cloud functions, see the info above).

Pretty awesome, isnā€™t it? But how do we get this running online? Letā€™s take a look at ZEIT now.

ZEIT now ā€” ā€œRealtime global deploymentsā€

Probably you already have heard of ZEIT now. Letā€™s see what ZEIT says about their own product:

now allows you to take your JavaScript (Node.js) or Docker powered websites, applications and services to the cloud with ease, speed and reliability.

Wouldnā€™t it be great to get all of the things online with just one command in the terminal? Since all dependencies are already set in package.json there is no further need of configuration to get the project running in the cloud.

How about just type

$ now

in the project root directory and the rest is done by the now cli? Seriously, itā€™s that easy!

First install now globally:

yarn global add now

Now you can run the cli of now! First time running, it will ask you to create an account and send you an e-mail to verify. Itā€™s done within seconds.
PromisešŸ¤ž.

And this is how a deployment looks like:

$ now
> Deploying ~/Websites/example-app under xxx@example.com
> Using Node.js 8.9.3 (default)
> Ready! https://example-app-pjigngjmxx.now.sh (copied to clipboard) [1s]
> You (xxx@example.com) are on the OSS plan. Your code and logs will be made public.
> NOTE: You can use `now --public` to skip this prompt
> Initializingā€¦
> Building
> ā–² npm install
> āœ“ Using "yarn.lock"
> ā§— Installing 1 main dependencyā€¦
> āœ“ Installed 48 modules [4s]
> ā–² npm start
> > example-app@1.0.0 start /home/nowuser/src
> > node server.js
> Server started on: 3000
> Deployment complete!

As you can see our app is running and we can open it on:

https://example-app-pjigngjmxx.now.sh

If you are using the free plan (OSS) you can skip the prompt of the now-cli telling you, that your code will be made public by adding --public.

Keep in mind that in free plan your whole code is available for people that have knowledge of the address. Just add /_src and you can see your code (and everyone else does).

For me personally there is nothing bad about it but obviously I donā€™t want my sensitive data to be public to everyone. Thatā€™s why we are using environment variables we work with. In the previous code you might have recognized code like process.env.DATABASE_URL. DATABASE_URL is sth. that we keep in our .env file (DATABASE_URL="https://example-app.firebaseio.com"). With this command you tell now to use it:

now --dotenv

Note: Donā€™t forget to add a .gitignore with .env in it so now doesnā€™t deploy it!

Maybe you have noticed that now adds random characters to each instance to create unique addresses. What about having a static address that is not changing everytime? Well, we can achieve this by giving the app an alias. We do this by adding a now.json file to the root and specify an alias:

With now $ now alias we can easily assign it:

$ now alias
> Assigning alias example-app to deployment...
> Success! example-app.now.sh now points to example-app-pjigngjmxx.now.sh! [6s]

We can even combine everything: $ now --dotenv --public && now alias

Donā€™t forget there is a limit of 3 max. instances in the free plan of now. In our case thatā€™s fine. The only problem is that after 3 instances, the cli is warning and we manually have to remove at least one instance to go on deploying:

Removing instances can be done using
$ now rm example-app-pjignghmxx

But as you can see, it needs the instance key which you can retrieve with
$ now ls

This is where now-clear by Tal Bereznitskey comes into play. Just install with $ yarn global add now-clear, get your now token and run it with your deployment name: $ now-clear -n example-app -t YOUR_TOKEN

If you donā€™t want to publish your sources, the quota is too low or you need individual domains, just take a look at the other plans of ZEIT now.

Altogether, this is our deployment command:

$ now-clear -n example-app -t OUR_TOKEN && now --dotenv --public && now alias

This performs:

  1. Clear previous instances (needed for the free plan, max. 3 instances)
  2. Deploy with environment variables and skip the prompt
  3. Link deployed instance with alias

We will shortly create a terminal alias or put everything in a bash script to keep things simple.

Summary

In our case this setup worked out really smoothly and fast. Which doesnā€™t mean thatā€™s the one way to go. Maybe itā€™s not flexible enough for all situations but we just needed a tiny helping layer between the SPA and a cloud database without having a huge tech stack. The deployment is super easy and saved us a lot of time.

If you liked the article, feel free to give us some claps šŸ‘‹
Do you have any comments or suggestions? Please donā€™t hesitate and leave us a message.

--

--