February 03, 2017 - VitoMd and the Evil Machine

Deploy a javascript/Node app to Heroku in 20 minutes

Intro

I created a static app in Javascript to organize ideas, tasks and information using bullet points and hashtags. It´s called Sorter and you can take a look here: Sorter. It sync notes to google drive using my other library gDriveSync.js.

I wanted to deploy the app somewhere for free so I decided to create a simple Node application to display the static app and deploy it to Heroku. You will need git, node, npm and heroku.

code

0) Setup

Create a new folder called StaticServer. Create a git repository.

mkdir StaticServer
cd StaticServer
git init

Create a .gitignore file to exclude node_modules

node_modules
npm-debug.log

1) Installing Express

First create a package.json file to add Express as a dependency.

npm init
npm install express --save

Heroku recommend to list the engines, so first get the version number for node and npm.

node -v
npm -v

We will need to add the engines to our package.json. Like this

{
  "name": "Sorter",
  "version": "1.0.0",
  "description": "Sorter is a webapp to organize ideas, tasks and information using bullet points and hashtags.",
  "main": "index.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.14.0"  
  },
  "engines": {
    "node": "6.4.x",
    "npm": "3.10.x"
  },  
  "author": "vitogit",
  "license": "MIT"
}

2) Creating the Server

Create a file server.js like this:

var express = require('express');
var app = express();
var fs = require('fs');
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 4000);
module.exports = {app}

It will show all static html pages from the public folder.

3) Procfile

We need to tell Heroku how to run our app. Just create a new file called Procfile with this content:

web: node server.js

4) Pushing to Heroku

Create a public folder and add some static html pages, then commit.

git add .
git commit -m "Initial commit"

Login to Herok, create the app and push.

heroku login
heroku create
git push heroku master

Finally just open the new deployed app and check that is working fine.

heroku open

Bonus: nodemon

You can use nodemon to reload html changes in folders while you are developing your app. Install it globally:

npm install -g nodemon

Add a script to the package.json to reload the server when js or html changes happens.

"dev": "nodemon server.js -e js,html",
Share this post on Twitter

Comments