I’ve been working with the MEAN stack, following an example in Jeff Dickey’s book: “Write Modern Web Apps with the MEAN Stack” to create a web application.  I had it working fine locally, but encountered a few problems when deploying the app in the cloud using Heroku, which is what I'm outlining in this post. I'll start with how I create the app from the web interface, and then configuring MongoDB and Gulp to work on Heroku. 

1. Create a Heroku App 

Here was my general process:

  1. Create a new app in from the Heroku web interface
  2. Clone my git repository and cd into my cloned project directory
  3. Then follow the instructions provided by heroku to log into and push the app up:

    If you haven't already, log in to your Heroku account and follow the prompts to create a new SSH public key.

    $ heroku login

    Clone the repository

    Use Git to clone social-app-test's source code to your local machine.

    $ heroku git:clone -a app-name
    $ cd app-name

    Deploy your changes

    Make some changes to the code you just cloned deploy them to Heroku using Git.

    $ git add .
    $ git commit -am "make it better"
    $ git push heroku master

At this stage, I was getting the following Heroku application error when visiting the URL of my new app:

Heroku Application Error

There were a couple problems causing this - the MongoDB connection is broken, and the gulp tasks aren't running. These problems are addressed below:

2. Fixing the MongoDB Connection

To run MongoDB on Heroku, you need to install it as a service for your app, which can be done in one line:

heroku addons:add mongolab  

Once MongoLab is installed, you’ll need to ensure your mongoose connection is set to use Heroku’s environmental variable, as well as your own (so you don't break how things work locally). That can be done really easily by adding the process.env.MONGOLAB_URL variable when using mongoose.connect(). For my app it was in my db.js file:

 

mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://localhost/social', function(){

console.log('mongodb connected');

})

 

3. Running gulp on Heroku

 To run the app locally, I was entering gulp dev from the console, which was running a bunch of tasks to build and serve the app. 

Of course, when you push the app to Heroku, this step is missing so the app never builds. This can be easily solved by modifying your package.json to include a start script which is always run by Heroku. In the start script, you can enter any tasks you want to run straight away - mine was gulp dev:

 

  "scripts": {

    "start": "gulp dev"

  }

Now you can commit and push those changes to Heroku and it should work. If it doesn’t, just run heroku logs from the terminal, and do some googling around the errors. 

What's next?

Doing the same thing with IBM Bluemix