Node.js on Azure gotchas

Two gotchas that gotch me when deploying a Node.js app on Azure:

1: Azure isn’t able to start your app

Azure starts your app using npm start. Try npm start locally before you deploy to Azure, and if doesn’t work (exits silently without starting your app) it’s possibly because node server.js wouldn’t start your app either!  That’s all npm start does by default.

You can rename to server.js to match convention, or you can specify an alternative start script in package.json:

  “scripts”: {“start”:”node <name of your script here>”}

for example for snowflake.js

  “scripts”: {“start”:”node snowflake.js”}

2: You think you’re letting Azure set port, but you copy-pasted buggy sample code

Azure sets environment variable PORT to tell your app what port to HTTP-listen on. Azure will forward the incoming requests on 443 & 80 to that port. So, you’ll need to write code to pick that environment variable value up and .listen() on it. Azure’s not the only Node.js host that does this; Heroku does the same.

Example code typically picks up the environment variable like this, providing a default of 1337 for when PORT isn’t set.

var port = process.env.PORT || 1337;

But I’ve seen this buggy sample code the Internet far too often:

var port = process.env.PORT | 1337; // DON’T DO THIS, THIS IS BITWISE OR

8000 | 1337 is 8057. Oops. Now your app’s not listening on the port that Azure chooses.