Firestore Saving User Data


Cloud Firestore + Authentication FTW

The last post on this site was about how Firebase’s Cloud Firestore was a great option for saving data, especially in new or prototype applications.

In a previous post I also showed how you can use Firebase’s handy authentication mechanism to easily register and authenticate users to your site.

This post will attempt to show how the Firestore and authentication mechanisms can be combined to store user preference information.

Authentication Recap

In the auth post we saw how easy it was to setup and that, when a user authenticates, they have a unique id when you can then use.


firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in. uid is now available to use
var uid = user.uid;


The code above shows how we can watch for when a user logs in. After they have logged in we can then use the uid as a unique identifier for each logged in user. The next step is to start creating some data in our Firestore that we can link to this authenticated user each time they log in.

Save User Related Data

Saving user related data e.g. profile information, with Cloud Firestore is easy. Once you have an authenticated user’s unique identifier you can start to save documents in your Firestore with the UID as an identifier. Each time the user logs in you just look up the document in your Firestore to retrieve the related information about this user/login.


firebase.auth().onAuthStateChanged(function(user) {

var dbUser = db.collection(‘users’)




someotherproperty: ‘some user preference’




In the code above we wait for the user to log in, retrieve their UID and create a document in the Firestore using the uid as the index. From this point we can add as many properties to this document that we need, and retrieve the information anytime the user logs in.

Simple stuff! Give Firebase a go, you won’t regret it.

Firebase Cloud Firestore


NoSQL, huh, whats is it good for?

I am not a huge fan of NoSQL. If you can keep your data structured, you should keep your data structured. Also, I have never, to date, worked on a project where a relational database was not scale-able enough to cater for the amount of data I needed to throw at it. NoSQL databases, like Firestore, have their uses, but for most production projects I’ve worked on so far, a relational database was either the ‘best’ choice or ‘good enough’.

However, sometimes, the structure of the data is unknown or likely to change. One such occasion is when you are starting out on a project. For prototype web applications I have found that NoSQL (Mongo, Firebase etc) can really speed up the initial stages of the project. Firebase’s new Cloud Firestore offering is a really useful NoSQL database for prototyping projects.

Real-time Database Vs Cloud Firestore

Firebase used to call its database offering ‘Realtime Database’ it now has a new offering called ‘Cloud Firestore’. Both are currently supported and available through the console, but it does appear that Firebase are trying to coax users to use the newer, but still in beta, Firestore.

The main difference between the two seems to be the data model. One of the frustrating things about the Realtime database was that you needed to de-normalize your data in order to use the queries effectively. If your data was hierarchical in nature you found yourself having to jump through hoops in order to use the realtime database effectively e.g. because you are always returned the entire sub-tree for a query, you needed to create separate trees for your data to avoid bloat in your result sets.

Cloud Firestore FTW

Firestore is not just any old NoSQL database, it has the following compelling features:

  • Easy to setup. The Firebase docs do a great job of helping you get started in whatever language you use (web, IOs, Android, Node, Go, Python, Java).
  • Easy to use. I have tried to think of a way that the Google team could have made it even easier to use the SDK… but failed.
  • Realtime. Real-time means real-time, try it out, create a simple project, hook your UI up to some data, watch the data change as you change the data in your console.
  • Scalable. So they say, sadly I’ve not had to use the scalability super powers yet.


Even though its still in beta, I would thoroughly recommend choosing Firestore over the realtime database for new projects. For existing projects, which currently use the realtime database, the choice is not as simple. Migrating to the Firestore is not a simple task due to the vastly different datamodels. Take a look at the pros and cons to determine if it is indeed worth the migration effort.


In the next blog post I’ll show how you can get started with Firestore and build upon the Authentication post to tie authentication events to saved user data.


Firebase Authentication


Tools For Your Tool-Belt

As a freelance developer its good to have a number of different tools in your tool-belt for when the situation demands. Firebase, and in particular, Firebase Authentication, has proven really useful over the past couple of years.


Most projects that I work on nowadays require some sort of user authentication. In the past I have used JWT or basic auth as my go-to solutions for authentication. However, even those these methods are fairly straightforward, I still had the nagging feeling that “This is a common problem, there must be a way to make this even easier.”.

JWT is great and easy to get started with but it is not always plain sailing; basic auth is well….. basic. JWT is very similar to Firebase Authentication in that you can use a 3rd party to authenticate users (using the Auth0 service) and not have to set up your own authentication server and process. However, manually persisting tokens on the client side and handling the clean up on expiry, logout etc, still felt verbose to a lazy dev like myself.

Firebase Auth

Firebase Authentication is easy to set up, the wide range of SDKs are easy to use, is free to start using, and “supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more”.

Most of my experience using Firebase authentication has been in web apps or hybrid mobile app development; below are some really quick steps on how to get started for web:

  1. Sign up for a Firebase account and create a new project.
  2. Choose “Add firebase to your web app” and follow the instructions i.e. include the JS library and add the configuration details to your app.
  3. Add a screen which asks the user for an email address and password. Then pass these details to the “createUserWithEmailAndPassword” SDK function to create a new user.
  4. Add another screen which asks for an email address and password, then pass these details to the “signInWithEmailAndPassword” function. When the function returns you should now have an authenticated user! I could go into more detail on the other methods you can use e.g. “signOut”, but most of them really are self-explanatory and the docs do a great job of showing you how.

Add a login screen with text boxes and a login/register button, then hook the button click to the Firebase SDK methods

Facebook, Google, Twitter, GitHub

To add Facebook, Google, Twitter or Github authentication just:

  1. Enable the required type of authentication through the “Authentication” tab on your Firebase console (following any specific instructions for each provider).
  2. Add a button to your login page for each provider you wish to use.
  3. Hook up the button click to use the appropriate SDK method on the client e.g. “signInWithPopup(new firebase.auth.GoogleAuthProvider())”
  4. After the user has authenticated themselves through the popup window, your call should return and you should now have a [Google] authenticated user.
  5. *A word of caution for hybrid mobile developers* Popups will not work on your hybrid mobile app, you will need to use native Facebook/Google libraries to achieve the same thing e.g. using facebook sign-in for Ionic.

Mobile, federated, logins are waaaaaay more difficult!

Populating Elastic With Your Database


The Problem

Recently I was tasked with providing fast full-text searching, across multiple tables, for a reasonably big database (~2m records).

Immediately I reached for some sort of Solr or Elastic solution. Being the lazy developer that I am, I chose the path of least resistance (most samples online on how to get started), and chose Elastic [edit: would seriously consider Angolia for my next project, if I had less than 10k records to index].

Getting Elastic set up was relatively simple. Having access to a few AWS credits, I used the AWS ElasticSearch service because I didn’t want the responsibility for maintaining the server.

Now to populate with some data.

Taking data from a database and putting it in an Elastic index must be a common scenario with lots of examples and help, right?

Well, not quite as common as I thought, and not as easy as I was hoping.

I was “hoping” for a nice simple user interface; point at my database, select what data I want, import into Elastic, done. I thought, with the relative maturity of Elastic, that it would be baked into the product, or someone would have created an add-on already. At the least, I thought, there would be a plethora of examples to show how to get data from a database to Elastic.

What I found was lacking, and its the reason why I’m making this post to help others looking to do something similar.


The currently recommended solution for indexing database data is Logstash (up until 2015 the recommended way was through Rivers).


Logstash. Looks great from the diagram

With Logstash you can connect to your data, filter it, transform it, and then add it to Elastic. Great!, just what I was looking.

Logstash takes quite a bit of work to set up and configure though. The setup is fairly straightforward; just download and install on Windows or Linux. After installation, there is no UI with Logstash, just access to a command line command, to which you supply configurations.

Unfortunately Logstash does not have a way to connect with databases out of the box. To connect logstash to your database you will first need to jump through a couple of hoops:

  1. You will need to install the JDBC plugin for Logstash, the instructions on how to do this can be found here.
  2. The JDBC plugin does not include any database drivers so you will need to find the driver you need and then download. I am mostly connecting to Postgres so I need to download the Postgres JDBC driver. Make a note of where you download this driver to, you will need the path to the driver to your configuration later.

Providing you have no issues with your Java installation, you should now be ready to go.

Logstash Configurations

Most of your time will be spent fine tuning configurations. Simple configurations are straight forward i.e. connect to a single table with basic field types and import into Elastic. Anything outside these parameters can be challenging.

A basic configuration to connect to a Postgres database and import into a new Elastic index could look something like this:


# file: simple-out.conf
input {
jdbc {
# Postgres jdbc connection string to our database, mydb
jdbc_connection_string = "jdbc:postgresql://localhost:5432/mydb"
# The user we wish to execute our statement as
jdbc_user = "postgres"
# password
jdbc_password = "mypassword"
# The path to our downloaded jdbc driver
jdbc_driver_library = "/path/to/postgresql-9.4-1201.jdbc41.jar"
# The name of the driver class for Postgresql
jdbc_driver_class = "org.postgresql.Driver"
# our query
statement = "SELECT * from contacts"
output {
elasticsearch {
protocol = http
index = "contacts"
document_type = "contact"
document_id = "%{uid}"
host = "https://urltomyelasticinstance"


The configuration file above can be run with the following Logstash command:

"\pathtologstashbindirectory\logstash.bat" -f simple-out.conf

The configuration, when run, will:
  1. Connect to the postgres database.
  2. Get all the data from the ‘contacts’ table.
  3. Connect to your elastic instance.
  4. Create a new index called ‘contacts’
  5. Create a new document type called ‘contact’
  6. Automatically create mappings for the fields in the contacts table.
  7. Populate the index with the data.
Easy, right?
The challenges come when your scenario deviates from this very simple example.
In the next post I’ll detail some of the issues that you might come across when deviating from this simple example.




Tech For Good – DigitalDNA – Hackathon 2017


Hackathon Success

As part of the DigitalDNA conference in Belfast in early June a hackathon was held in the wee hours around the topic of youth unemployment.

DigitalDNA: Tech Conference Held Annually In Belfast

The challenge was to develop, in teams, a app/service/tool to help alleviate youth unemployment, within 12 hours. The prize? A trip to Dubai to present to a VC firm.

Guess what, our team won, woot!

Domain Experts

At the end of the first day of the conference, while the ‘corporates’ were milling out, the ‘have-a-go techies’ started appearing from the shadows.

Panel Discussions

The hackathon started at 4pm with some invaluable panel discussion from youth workers around the topics involved with youth engagement.

The insight learned from these discussions, and from further engagement with these domain experts, really helped to shape everyone’s thoughts around potential solutions.

Programmer Fwends!

And then, we were ready to go…….almost.

First we needed a team.

Now, I’m a decent programmer, but I know my [many] limitations. Entering a hackathon on my own was not on my radar; I wanted to learn from others experiences and skills in this 12 hour window.

Conor Graham helped to broker team alliances

Luckily, there were others in a similar position, and we quickly formed a team; myself, Luke Roantree & Hussien Elmi (we did have Samir Thapa at the start but unfortunately he had to leave early on and could not return).

From working with Luke’s father at Spatialest and hearing good reports from friends about Hussien at Deloitte, I knew we had a great team.

Loads of Time?

12 hours to bring an idea to life may seem an achievable goal at first sight, that’s only if you have a clear idea in the first place.

Distilling Ideas

Creating and distilling ideas is a time-consuming process, but fortunately the domain experts were on-hand to help. By bouncing ideas off the experts our team managed to agree on an initial direction and set to work.

Ready To Rock

With only about 8 hours to go, we were ready to rock; we were going to build an app.

Hussien Ready To Rock

Myself and Hussien had previously met at an Ionic meetup where I was speaking; using this hybrid mobile app technology was a no-brainer for us. With Ionic you can build cross platform apps very quickly; time was of the essence. Although Luke had not used the technology before we knew he was a whizz at anything he put his mind to.

The Graft

Pumped up on red bull, coffee and pizza all the teams really started getting into their stride around 11pm.

Red Bull (other sleep deprivation agents are available)

After the original chatter in the early evening all the teams were furiously coding away. With the realization rapidly dawning that less than 5 hours were left on the clock, the teams had partitioned out their work and were now working in silos.


Funny thing about coffee and Red Bull, what goes up, must come down.

Around 2am the effects of the long day and caffeine started taking its toll. Dreary eyed developers roamed the conference space and focus started shifting away from computer screens to thoughts of bed.

After 3am very few people were left and eventually even our team decided to call it a ‘day’.

After gathering up as many free cupcakes, cold pizza, beer and crisps as we could humanly carry (admittedly it was a lot!), we started to make our way home on foot. We must have looked a random bunch on the Ormeau Road at 3:30am, but to my surprise, not many people batted an eyelid at 3 geeks laden with that many munchies at that time in the morning, go figure!?!?

Presentation Time

The presentations were to take place in the afternoon of the 2nd day of DigitalDNA conference.

Whats my potential hybrid App

By this stage our app had quite a polished feel. Working with collaboration tools such as Trello, GitHub and Slack we had worked well as a team and had managed to produce an immense amount of output in a short period of time.

I had my daughter’s sports day to attend so it was up to the Luke and Hussien to present. They both knocked it out of the park!

The presentation was flawless and the demo was impressive. The judges were impressed not only with how polished the app was but also that the domain experts views’ had been taken on board.

Luke And Hussien Recognized for their hard work

In the end credit must go to all the teams. Every team worked hard on trying to find ways to alleviate the globally transferable issue of youth unemployment.

Kudos also to everyone involved in making the DigitalDNA conference happen. The conference brought together all that is good about the tech scene in Northern Ireland and beyond.

Big thanks also to the organizers and sponsors of the hackathon; it was really well run and we enjoyed every minute of it (even at 3.30 in the morning).

Hopefully all goes well in Dubai with our presentation to Falcon & Associates in November. However, with such a capable team and great mentors from the HackForGood team, we won’t disappoint.

WordPress REST API – Part 4 – Ionic 3


Ionic 3 + Angular 4

This post follows on from posts about hybrid mobile app development using the new WordPress REST API and Ionic: Part 1, Part 2, Part 3

Part 3 contained a walk through of the Ionic 1 code. What follows is a walk through of the code for an Ionic 3 app.

From following the steps in part 2 By now you should have a [very basic] Ionic app running in your browser. The app will allow you to:

  • Authenticate with your remote, WordPress REST API enabled, website.
  • Make a post from the mobile app to your WordPress site.
Ionic 3 to WordPress

Ionic 3 to WordPress

Pretty simple stuff.

The code that performs the magic is pretty simple too.

Ionic Project Structure (Ionic 3)

Ionic 3 Project Structure

Ionic 3 Project Structure

As you can see from the folder structure below there are quite a few folders in our Ionic App.

However, the important files and folders are as follows:

  • src/app: The 1st component to be shown on screen for the app. Things like navigation routes are configured here.
  • src/pages: The pages for the app are in here i.e. the Login and Report pages.
  • src/providers: This folder contains reusable services to perform business logic e.g. authentication and connection to WordPress
  • ionic.config.json: This file contains configuration options for the app. In Part 2, we changed a setting in this file to point to our WordPress site.

The folder structure is much like any other Angular 4 application, so we will head straight to the code to see what the key lines are:


As this component is the entry component for this app we configure if the user should be navigated to the Login or Report screens on startup.

In this file we:

  • Start listening to our UserProvider (see user.provider.ts) to see if the logged in/out event is fired.
  • If the logged in event fires navigate to the Report page, otherwise go to the Login page.

private events: Events,
private userData: UserProvider
) {
// start listening to login and log out events
// check to see if user has logged in before
// if they have there will be a logged in event fired

listenToLoginEvents() {
// if the user is logged in then navigate to the Report page‘user:login’, () => this.rootPage = Report);‘user:logout’, () => this.rootPage = Login);


In the previous step we saw that a UserProvider was referenced; this provider is declared in user.provider.ts.

The main job of the UserProvider is to check the username and password in order to receive an authentication token from the WordPress server. This job is outlined in the ‘login’ function.

The login function will:

  • Contact the WordPress server with the username and password to ask for an authentication token.
  • If successful the token will be used in every subsequent http call to the WordPress server. The way we do this is by creating our own http client and injecting the token in every header (see http-client.ts).
  • The authentication token will be stored in case the user comes back to the app at a later date.
  • An event is fired to tell subscribers that the user is now logged in.

// this is a unique token for storing auth tokens in your local storage
// for later use
AUTHTOKEN: string = "myauthtokenkey";

// determine if the user/password can be authenticated and fire an event when finished
login(username, password) {
let data = { username: username, password: password };
// remove any existing auth tokens from local storage
// the important bit, contact the WP end point and ask for a token‘/server/wp-json/jwt-auth/v1/token’, data).map(res => res.json())
.subscribe(response => {
// great we are authenticated, save the token in localstorage for future use
this.stor.set(this.AUTHTOKEN, response.token);
// and start using the token in every subsequent hhtp request to the WP server
this.http.addHeader(‘Authorization’, ‘Bearer ‘ + response.token);
// fire an event to say we are authenticated‘user:login’);
err => console.log(err)


The HttpClient class has a very simple purpose; inject our authentication header into every Get and Post operation we make to the WordPress server.


// inject the header to every get or post operation
get(url) {
return this.http.get(url, {
headers: this.headers
post(url, data) {
return, data, {
headers: this.headers



The WordPress provider has a single function: try to post the score and report data to WordPress.

The ‘createReport’ function:

  • Sends a message to the app to tell it that a save operation has started (for the purpose of showing spinners etc).
  • Sets the JSON data required by the WordPress REST API posts call (the full range of options can be seen here).
  • Posts the information to our WordPress website.
  • Gets back a success/failure message.
  • Lets the App know we have finished the save.

createReport(score: string, report: string) {
// let the app know we have started a save operation
// to show spinners etc‘wordpress:savestatus’, { state: ‘saving’ });
// set the JSON data for the call
// see for options
let data = {
title: score,
excerpt: report,
content: report,
status: ‘publish’
// the important bit, make a request to the server to create a new post
// The Authentication header will be added to the request automatically by our Interceptor service‘/server/wp-json/wp/v2/posts’, data).subscribe(data => {
// tell the app that the operation was a success‘wordpress:savestatus’, { state: ‘finished’ });‘wordpress:createdreport’);
}, error => {‘wordpress:savestatus’, { state: ‘error’, message: error });


The login page is very simple. When the login button is pressed, the username and password input in the textboxes are passed to our UserProvider service.


username: string;
password: string;
constructor(public UserProvider: UserProvider) {
login() {
this.UserProvider.login(this.username, this.password);



Again the report page is very simple. When the report button is pressed, the score and report input in the textboxes are passed to our WordPress service.

constructor(private events: Events, private wordpress: WordPressProvider, private user: UserProvider, private loadingCtrl: LoadingController, private toastCtrl: ToastController) {
createReport() {


Any Questions?

That’s basically all there is to it.

If you have any questions, or any amendments that I can make to the Github repo, then please comment below….

Scaling WordPress


*In this post I will attempt describe how you can prepare your WordPress site so that it can be scaled.

WordPress is generally not scalable

The usual deployment scenario is to have the database, core files, user files and web server, all on the same server.

In this scenario, the only scaling that can be performed, is to keep adding memory and power to a single server (vertical scaling).

Scaling Options

‘Scaling vertically’, which is also called ‘scaling up’, usually requires downtime while new resources are being added and encounter hardware limits. When Amazon RDS customers need to scale vertically, for example, they can switch from a smaller to a bigger machine, but Amazon’s largest RDS instance has only 68 GB of memory.

‘Scaling horizontally’ means that you add scale by adding more machines to your pool of resources. With horizontal scaling it is often easier to scale dynamically by adding more machines into the existing pool.

Horizontal vs Vertical Scaling

Horizontal Scaling For WordPress

To enable horizontal scaling for WordPress we need to first decouple the various parts from each other (web server, files and database). Once decoupled, we can place each part on separate servers and scale them as necessary.

Decouple Before Scaling

Decoupling the database is ‘easy’. You can easily move your WordPress database to its own server by taking a backup and migrating (guess what, there’s a plugin for that). Once moved, you just need to change the ‘DB_HOST’ value in your wp-config file.

Decoupling the web server from the files (WordPress core files and media library files) is more complicated. From what I can gather there are 2 options for doing this:

  1. Host only your library files on a remote cloud server. This article explains how to achieve this.
  2. Host both your core files and library files on a mounted volume linked to a remote cloud server. This article explains how to link your uploads folder to cloud storage, but you equally link your entire WordPress folder.

I prefer option 2 because:

  • Option 1 keeps your core files coupled to the web server.
  • It also only caters for new uploads, not existing files too.
  • In addition, it involves rewriting the url links for your files.
  • Option 2 keeps your url links the same so you revert back or change cloud provider easier.

However option 2 is way more complicated to set up. In my next post I will show how Docker can help with this process.

Decoupling complete, now scale!

You can now scale your WordPress site.

In the next post I will show how to use Docker, in particular Docker Cloud, to make this process painless.

Ionic 2 First Impressions


Even More Productivity?

After experiencing the immense productivity gains from using Ionic for mobile development, surely using Ionic 2 would be even more productive, right?!!?.

Sadly. No. Not yet, at least.

I had hoped to be writing a post telling everyone how awesome Ionic 2 is.

I had hoped to be falling over myself to tell you about how quickly it was to get started, the incredible workflow, the intuitiveness of the framework, the terseness of the code.

Instead, what follows is a moan colored by disappointment and frustration from using Ionic 2, Typescript & Angular 2.


Ionic, Angular 2 And Typescript

Ionic is a cross platform mobile app framework. It uses Html & JavaScript (Angular) to create mobile apps that can be run on Android and/or IOs.

Ionic 2 is more of the same, but with a few notable differences. You will, inevitably, be using Angular 2 and Typescript to create your apps.

Angular is a JavaScript framework which makes creating single page web apps easier than just using plain JavaScript. Angular 2 is google’s second attempt at the framework, and a significant departure from the first.

Typescript is a superscript of JavaScript. It allows you to write tidier, more elegant, maintainable, JavaScript.

Now, both Angular 2 and Typescript are great in my book, but they are ‘new’. This leads me to my first gripe about the Ionic 2 stack, the learning curve:


Gripe 1: The Learning Curve

There are several steep learning curves involved with the Ionic 2 stack.

Typescript is a big departure from vanilla JavaScript. The syntax should not be alien to anyone who currently uses ES6/ES2015 but it will still take some getting used to.

The other steep learning curve is with Angular 2. Although the syntax in Angular 2 is more elegant and easier to learn than Angular 1, they both have steep learning curves.

Also, there are also changes with Ionic 2 which are a departure from Ionic 1 which you must learn. However these changes are not as severe as the changes in the Angular 2 and using Typescript.



Gripe 2: Beta

Ionic 2 is a beta.

Angular 2 is just out of beta.

Typescript is relatively new.

If you regularly program via stack overflow ‘copy and paste’ you will be frustrated by the lack of help and the ‘out-of-date’ help that you find.


Gripe 3: The Showstopper: Transpiling & Bundling

Ok, here’s the thing that’s eating me most: transpiling & bundling.

This is not a gripe with Ionic 2 per se; it is a gripe about modern web development.

Before, with Ionic 1, using the web tools to debug your app, feedback was instant. You made a change to your code and the changes were reflected immediately on screen.

Now, with Ionic 2, when you save, all your code needs compiled from typescript to something the browser can understand. On top of that, Ionic 2 now bundles your application for use in the browser every time a change, no matter how small, is made.

The upshot, is that when you save even a small project, the wait before you get feedback is greatly increased. I have spent my time waiting 30 seconds upwards waiting for a simple change in my JavaScript to take effect on screen!.

(Maybe I am using it wrong? Please, please, correct me if I am.)

This is a BIG problem for me. The thing I liked most about Ionic 1 (and web development in general) was how immediate the feedback loop was.

Things were so much more productive in the web world compared to using compiled languages. Working with a scripting language had its issues, but it felt so productive not having to wait on the compiler to finish.

Transpilers & bundlers have added a compile step to web development which affects productivity.


Largely due to my opinion on the frustrating feedback loop with Ionic 2, I will not be using Ionic 2 for new projects yet.

Sure, there are a lot of benefits from using Typescript to create a maintainable code base and productivity gains from using using Angular 2, but these are currently outweighed by the negatives.

Ionic 1 is still more productive for me and I will be continuing to use it in the near future.

As always, this is just my opinion. If I am missing something obvious, or have got this horribly wrong, please correct me in the comments below….

WordPress REST API – Part 3 – Ionic 1


Code Run Through

This post follows on from posts about hybrid mobile app development using the new WordPress REST API and Ionic: Part 1, Part 2

What follows is a run through of the import parts of the code, for the application shown in Part 2.

By now you should have a [very basic] Ionic app running in your browser. The app will allow you to:

  • Log into your remote, WordPress REST API enabled, website.
  • Make a post from the mobile app to your WordPress site.

Pretty simple stuff.

The code that performs the magic is pretty simple too.

*I have created both an Ionic 1 and Ionic 3 repo for the App code. However, below I describe the structure for the Ionic 1 repo only.

Ionic Project Structure (Ionic 1)

Ionic 1 Folder Structure

Ionic Folder Stucture

As you can see from the folder structure below there are quite a few folders in our Ionic App.

However, the important files and folders are as follows:

  • www/js: This folder contains all the Javascript code for the app.
  • www/js/app.js: The main entry point for the app. Things like routes are configured here.
  • www/js/controllers.js: The logic behind what happens on the screens is placed inside this file e.g. what should happen when the login button is pressed.
  • www/js/services.js: Reusable services to perform business logic e.g. authentication and connection to WordPress
  • www/templates: This folder contains the html for screen in the app.
  • ionic.config.json: This file contains configuration options for the app. In Part 2, we changed a setting in this file to point to our WordPress site.

The folder structure is much like any other Angular application, so we will head straight to the code to see what the key lines are:


In app.js we configure the Angular app before it runs.

In this file we state:

  • What our routes are i.e. what are the urls for our app, what html should be loaded and what Javascript files should control the html.

// Ionic uses AngularUI Router which uses the concept of states
// Learn more here:
// Set up the various states which the app can be in.
// Each state’s controller can be found in controllers.js
.state(‘login’, {
url: ‘/login’,
templateUrl: ‘templates/login.html’,
controller: ‘LoginCtrl’
.state(‘report’, {
url: ‘/report’,
templateUrl: ‘templates/report.html’,
controller: ‘ReportCtrl’
// if none of the above states are matched, use this as the fallback

  • Any injectors/interceptors we want to use. We will see later that, when we get an authentication token, we want this to be automatically passed to every subsequent HTTP call we make. An interceptor is a way of achieving this.


The controllers.js file contains the logic for the Login and Report screens.

The LoginController has one function: try to login when the user clicks the Login button

$scope.login = function () {
// contact our login service with the data from the username and password fields
LoginService.loginUser($, $ (data) {
// if it is a success, go to the Report screen
}, function (data) {
// if there is an error pop it up onscreen
var alertPopup = $ionicPopup.alert({
title: ‘Login failed!’,
template: ‘Please check your credentials!’


The ReportController has a single function too: try to post the score and report data to WordPress (though our WordPress service).

$scope.createReport = function () {
// show a saving… message while we contact the service
template: ‘Saving…’
// pass through the values from the score and report fields to the service
WordPressService.createReport($, $, failure);

Both controllers are very simple, it is in the Services.js where the real work is performed.


The services.js is the work horse of the app, it contains 3x services:

  • LoginService. This service is used to contact a WordPress REST API end point and request a JWT authentication token.

// the important bit, contact the end point and ask for a token
$‘/server/wp-json/jwt-auth/v1/token’, data).error(function (error) {
}).success(function (data) {
// you are now logged in, save to session storage, the auth interceptor will pick up
// and add to each request
$window.sessionStorage.token = data.token;

  • WordPressService. The WordPress service contacts our WordPress REST Api and tries to create a post.

var data = {
title: score,
excerpt: report,
content: report,
status: ‘publish’
// the important bit, make a request to the server to create a new post
// The Authentication header will be added to the request automatically by our Interceptor service
$‘/server/wp-json/wp/v2/posts’, data).error(function (error) {
}).success(function (data) {

  • AuthInterceptor. The interceptor service checks localstorage to see if we were given a token, if we have, then it adds it to every Http request.

request: function (config) {
config.headers = config.headers || {};
//if there is a token, add it to the request
if ($window.sessionStorage.token) {
config.headers.Authorization = ‘Bearer ‘ + $window.sessionStorage.token;
return config;

Any Questions?

That’s basically all there is to it.

If you have any questions, or any amendments that I can make to the Github repo, then please comment below….

WordPress REST API – Part 2


This post follows on from a previous post, espousing the virtues of the WordPress REST API for hybrid mobile app development.


At the 2016 WordCamp in Belfast, I gave a talk about using the WordPress REST API for mobile development. I gave two code walk throughs at the conference; what follows is a walk through of the football mobile app.

The football app uses Ionic to create a cross platform mobile app that:

  • Connects to a remote, REST API enabled, WordPress site.
  • Authenticates a username and password from the device (using JWT – JSON Web Tokens).
  • Shows a ‘Result’ screen. The screen allows users to input a score and match report.
  • Posts this ‘Result’ to the remote WordPress site.

N.B. All the Ionic 1 code is available on Github. There is also an Ionic 3 code repo available here.

The steps to create a shiny new mobile app, which allows soccer coaches to post match results from their phones, is as follows:

Ionic 3 to WordPress

Ionic 3 to WordPress

WordPress Site

We need to first create a WordPress website which will act as our back end engine to our app.

*Also on some servers you will need to enable http auth in your .htaccess file

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

Mobile App

  • Install Node on your machine.
  • Install Ionic and Cordova using the following NPM command/cmd:
    npm install -g cordova ionic
  • Download the github code (cd to the folder you want to put it in first)
    git clone

    Or for Ionic 3

    git clone
  • Using the command line navigate (cd) into the created directory
cd wp-rest-api-ionic
  • Get node to install Install the projects dependencies
npm install
  • Change the ionic.config.json file to point to the URL of your new WordPress site
     "name": "teamthingmobile",
     "app_id": "",
     "proxies": [
     "path": "/server",
     "proxyUrl": ""
  • Start Ionic to show a web verison of your app
    ionic serve


    You should now have a working mobile app, executing in your browser, which you can now use your WordPress credentials to login.

If not? Give me a shout below…….

In the next post I will highlight the important code in the sample, and explain what it means.

*For an Ionic 3 version of the code see this post.