Node.js for Rails developers, Part 7 (Deploying to Heroku)

This post is part of a series for Rails developers who want to get started with Node.js.
In one of the two alternative previous posts, we connected our application to a datastore (PostgreSQL or MongoDB).
In this post we will deploy our Node app to a production Heroku server.
There are some minor differences in the process depending on your choice of datastore.

Installing Addons

Application Configuration

After configuring the application’s Heroku production environment, we need to reconfigure the application according to Heroku specifications.

Production Web Server

Add a Procfile which specifies a command to start the production web server.

touch Procfile

Edit Procfile according to the following template:

# Procfile
web: node ./bin/www

NOTE: We’re not using Nodemon in production.

Engines and Deploy Scripts

Modify package.json to include engines and deploy scripts, as necessary. Find your own engine versions with node -v and npm -v, respectively. Specify database preparation commands and other start-up scrips using the scripts["heroku-prebuild"] and scripts["heroku-postbuild"] configuration variables. These commands will be run during each deployment. Edit package.json according to the following template:

//package.json{//..."engines":{"node":"5.9.1","npm":"3.7.3"},"scripts":{"start":"nodemon ./bin/www","test":"echo 'This is for running tests like ... mocha.')","postinstall":"echo 'This is when you would run a bower installation or grunt build.')","heroku-prebuild":"echo 'This runs before Heroku installs your dependencies.'","heroku-postbuild":"echo 'This runs afterwards.'"},//...}

Specify command(s) to migrate and seed the production database upon each deployment.

Production Session Storage

Our app’s flash messaging requires session storage. The default session storage in development environments is MemoryStore, but Herokusays this is not a best practice in production applications. HerokurecommendsRedis for session storage, but we don’t need to add another dependency to our technology stack. Let’s instead use the datastore we chose in the previous post.

Option A - PostgreSQL Session Store

If you chose a PostgreSQL datastore, let’s use the connect-session-knex module to handle session storage.

npm install connect-session-knex --save

Configure the application to use this module by editing the contents of app.js according to the following template: