Code snippets, tutorials and software engineering.

Introduction

Deployment, the final test to see if all your hard work will pay off. Deploying web applications can be daunting. Seeing your finished work fail on the web server as opposed to it succeeding on your local machine is a question I'm sure many developers struggle with. In this article, we will be deploying a small MERN application to the web using Heroku.

This will be a continuation of my previous article about creating your first MERN application. It can be viewed here. I will show you the necessary steps to deploy this web app. This will include installing some npm packages, editing certain files, and working with the Heroku dashboard to ensure everything is deployed correctly. We will then be given a URL of our newly launched web application for everyone to use and see.

Why Heroku

While there are many services for deploying apps, we will be going with Heroku for this example. Because of its flexibility and ease of use, it is best suitable for small-scale projects or teams. In our example, a simple MERN application, Heroku will work just fine. While Heroku may have options for pricing, we will strictly be using their free services for our project. Signing up is simple and once created, you can now use the Heroku CLI to connect your app on your local machine to Heroku. We will explain this in the next few sections.

Setting up the app for Deployment

We will first need to add a few scripts in our package.json. When we last visited this application, our file structure looked like this:

googlebooks
|-- package.json
|-- package-lock.json
|-- server.js
|-- node_modules/
|-- db/
|-- models/
|-- routes/
|-- client/

Let's add the following to our scripts:

"scripts": {
  "build": "cd client && npm run build",
  "heroku-postbuild": "npm run build"
}

The heroku-postbuild script is necessary to avoid complications when deploying. This will tell Heroku to put its output files created by npm run build into client/build.

If we check back to our server.js file, we will see how necessary running the previous script is. In server.js, we had the following lines:

// lines 6-8
if (process.env.NODE_ENV === 'production') {
  app.use(express.static(join(__dirname, 'client', 'build')))
}

// lines 15-19
if (process.env.NODE_ENV === 'production') {
  app.get('/*', (req, res) => {
    res.sendFile(join(__dirname, 'client', 'build', 'index.html'))
  })
}

Here we check if our node environment is in production. Heroku will automatically assign production to NODE_ENV, so we will then be serving output files in client/build to our Express app. This command will run prior to pushing to Heroku and will build our static pages for deployment.

Once this has been done, we can move onto setting up our Heroku app.

Deploying using Heroku

In our root directory, we will run the command below:

heroku login

Here we will log in using the Heroku credentials that we used to set up our account. This will ensure that our app is associated with our Heroku account so that we can access the application in the Heroku dashboard.

Once we have logged in, we can create our Heroku app. We can do this by running the following command in our terminal:

heroku create

This will result in the following output:

Creating app... done, ⬢ dry-gorge-38569
https://dry-gorge-38569.herokuapp.com/ | https://git.heroku.com/dry-gorge-38569.git

Our newly created Heroku app is named dry-gorge-38569. Yours will differ, but once created, you can open up your Heroku dashboard and view all your apps.

Go ahead and select your app. You will be shown a dashboard of your app. There will be a number of tabs near the top. Select Settings. Under Settings, there is a section named Config Vars. Click the Reveal Config Vars button and you will be prompted to add a key-value pair. Here we will add the MONGODB_URI connection string from our MongoDB collection. For the key, name it MONGODB_URI. For the value, we will need our connection string. More information on how to retrieve it can be found here. In our case, the connection string reads similar to mongodb+srv://.../<collection>?retryWrites=true&w=majority. Be sure to include your username and password where necessary. If you happen to also be using the MONGODB_URI string for your localhost, be sure to hide the string in a .env file to ensure your username and password aren't open to the public. For <collection>, we can put googlebooks, as this is the collection for our database for this app. Go ahead and add this config var. This will ensure that our app can connect to our database.

As shown in the last article, we connect to our database using the following in our db/index.js file:

module.exports = require('mongoose').connect(process.env.MONGODB_URI || 'mongodb://localhost/googlebooks', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
  useFindAndModify: false
})

Since we are trying to deploy, we won't be using our localhost server for our database. We will connect through the process.env.MONGODB_URI variable, which we provided in Config Vars for our app.

Now we can push our code to Heroku. Before we can do so, let's first ensure all our code is pushed up to our repository. Make sure your code is pushed to your master branch.

git push origin master

After you've successfully pushed your code, push to Heroku.

git push heroku master

After running this command, you'll have a long output in your terminal of Heroku building your deployed app. The end of the output will have a similar result:

remote:        https://dry-gorge-38569.herokuapp.com/ deployed to Heroku
remote: 
remote: Verifying deploy... done.
To https://git.heroku.com/dry-gorge-38569.git
 * [new branch]      master -> master

Here you will find your deployed application URL. In our case, the URL is https://dry-gorge-38569.herokuapp.com/. If we visit it, we will find a working application. If you run into any trouble while deploying your app, visit this page for more information on how to troubleshoot Node.js deployments. If you decide to make any changes to your app, make sure to push to your repository before again pushing to Heroku. Simply run these two commands:

git push origin master
git push heroku master

All Done

Go ahead and view the URL of your app. For my example, click the link above. Again, this is a continuation of my previous article on how to create a simple MERN app, which can be viewed here. Now you've got a fully deployed MERN application on Heroku. Congrats and happy coding your next application!

You’ve successfully subscribed to Into Code
Welcome back! You’ve successfully signed in.
Great! You’ve successfully signed up.
Your link has expired
Success! Check your email for magic link to sign-in.