December 4, 2016

Launching a Node.js app with Heroku

Yesterday I experimented with my first Node.js app and launched it on Heroku: https://friendly-cats.herokuapp.com/

Here are some of the steps I took:

Creating my Node.js server

I used Express to create a bare-bones Node.js framework for my app. You should check out their Express Generator tool for quickly generating an application skeleton.

Adding Middleware

Once the framework was there, I wanted to add Sass and watch + compile my style updates on the fly. To do this, I installed the node-sass-middleware Node module via NPM and then included it in my app.js file:

Toward the top of the file, I initialized the middleware.

var sassMiddleware = require('node-sass-middleware');

And then, right before the line...

app.use(express.static(path.join(__dirname, 'public')));

I added:

app.use(sassMiddleware({
  src: __dirname + '/sass',
  dest: __dirname + '/public/stylesheets',
  prefix:  '/stylesheets',
  debug: true,  
}));

This added a /sass folder (alongside /public, /views, /app.js, etc.) to my project. Whenever I ran my server locally, my styles would be watched + compiled to /public/stylesheets automatically.

Deploying to Heroku

It was extremely painless to deploy my app to Heroku. I mostly followed the steps Heroku published here, but here are the few important things to note:

  1. Make sure your package.json is up to date! You may be using Node modules locally that are NOT properly listed (with correct version number) in your package.json file, which means that when you deploy to Heroku, your app won't be able to find critical module dependencies it needs to run.
  2. Add your engines to package.json! You need to list both your Node version and your NPM version as engines in your package.json file, and it is important that their version numbers match what you are using locally.
  3. Specify a buildpack! You need to specify a buildpack so that Heroku is certain that your app is a Node.js app. Heroku has published awesome documentation about this on their website.

When I first deployed my app, the build went fine. However, I went to view the app, I received the dreaded "Application Error" page, directing me to "Check the logs." When I checked my logs, I saw the following: "Error: Cannot find module 'node-sass-middleware'." It turns out that my node-sass-middleware module had not been added to package.json. After manually adding the missing module and recommitting my package.json file, the app loaded just fine.