Auto Deployment for Node.js and GitHub

Posted on: 3 January 2017

Auto deployment of code would not only save me time, it would ensures that my repository is deployed in the same manner with every push; without the need of ssh'ing into the server. I recently spent some time exploring the best solution to auto deployment with GitHub using private token keys (I did not want to use SSH for this).

For a project I am currently working on, I needed the ability to push (or commit) updates to my master Git repository and then forward to them to a server. There are many solutions out there, but they were over engineered and complex. I just wanted a simple solution that works with node.js. This would enable me to embed the update within my current API structure without the need of running additional node.js instances.

After some searching I found a package called node-cd, which is a great little repo that is suitable for GitHub, BitBucket and Contentful. However, I wanted to customise it to function on private (but also public) repositories in GitHub, to function with npm install on my node.js application seamlessly and to integrate into my project.

You can find my solution on GitHub here. This is a scrappy hack that I would not use in a production enviorment.

I will briefly explain some aspects of the code and what you need to get started. The code has been tested using a MEAN image on a Digital Ocean droplet.

GitHub Private Token

Personal access tokens function like ordinary OAuth access tokens. They can be used instead of a password for Git over HTTPS, such as when we are required to pull a repository. A guide to create your personal access token is available here.

Web Hooks

To automate the process you will need to create a Webhook with the Git repository. This will broadcast to a defined URL when a commit/push has been performed. You will need to ensure that it is a totally anonymous link that no one can guess. See the router.js for an example.

If you are seeking to use this in production I would recommend you add additional security features.

Shell Script

To automate the install process, I decided to utilise a shell script; this will run every time there is a commit to the repository. An example of the code is below