Subscribe for tips on developing apps with Angular and Ionic

How To Create A Node.js Microservice For Your Ionic App

Menu

In my previous post I created an Ionic 2 app that reads the posts from a Facebook Page and displays them in the app. I also mentioned that hard coding the Access Token for the Facebook Graph API within the app wasn't ideal, since it can be stolen by anyone who decompiles your app.

In this post we'll create a very simple Node.js service that will handle the call to the Facebook Graph API for us, so we don't need to include the Access Token in our Ionic app anymore.

Download complete app source code

Enter your email address to download the source code for this tutorial.

Node.js and microservices

Node.js is a JavaScript runtime which you can use on a server to run JavaScript code. This enables frontend developers to create web services using JavaScript.

There are a couple of different frameworks built on top of Node.js that you can use to create web services, the most popular one being Express.

However, I recently stumbled upon this excellent post about building microservices with Node.js using micro, a lightweight library that's very easy to use.

A microservice is a service that does just one thing and can be deployed independently from other (micro)services.

I thought it was a perfect fit for the service I wanted to create in this tutorial. So, enough background information, let's code!

Setup service

We'll start by creating a directory for our service and creating a package.json file in it.

Create index.js

As you can see in the package.json, our main entry point for the service is index.js, so let's go ahead and create that file. We can write our code in ES6 (ES2015) because it's supported by Node.js. If you want to use TypeScript, you'll have to set up the transpilation to ES6.

I'm not going to go through the details of the Facebook Graph API here, you can learn more about it in my previous tutorial.

We're using require to import the request module we installed earlier and we're also importing url which is a core Node.js module.

To create the microservice we only need to export a function that takes in a request and a response parameter.

We parse the request url with url.parse to get the name of the Facebook Page we want to query and then we use request to do the request to the Facebook Graph API and pipe the output into the response of our microservice.

So that means we're just passing through whatever we received from the Facebook API. You don't have to do it that way, you can also do some processing on the response from Facebook before you make your own response to send back to the client.