Heroku Setup For MERN Stack Applications

Introduction

Heroku is a cloud service platform that enables simple application development and deployment. Since the Heroku platform manages hardware and servers, businesses that use Heroku are able to focus on perfecting their apps and not the infrastructure that supports them.

Heroku is based on a managed container system. It has integrated data services and a powerful ecosystem for deploying and running modern applications.

Applications as services use containers which are designed to package and run services. Applications that are run on Heroku have unique domain names which are used to route HTTP requests to the correct container. These containers are called dynos.

Heroku Setup

Basic Setup

  • Once the application you want to deploy is ready, download the Heroku CLI installer and install it. Also check npm, node and git versions.
    npm --version
    node --version
    git --version
    
  • Login to your Heroku account ( create one if you don't have one already ). You can log in using heroku login

Deploying Your Application

  • To create a container for your application, type heroku create This prepares Heroku to receive your source code.
  • Once the app has been created, push your code to the heroku remote. You can do this by using git push heroku main

    Note! This step will not work if your root directory (or directory where git is initialized) does not have a package.json file.

  • If your code is on a branch other than main or master, use git push heroku branch_name : main This builds and deploys your application.
  • To check if atleast one instance of your application is running, try heroku ps : scale web=1
  • You can visit the URL seen to open your app or you can type in heroku open on the CLI to open the application.

    To fetch data from the application, you can use this URL.

heroku create
//Your app will be created with a random name and a URL will be generated.

git push heroku main
//App will be deployed to heroku.

Once you've added changes to your git repo, make sure to push changes to the heroku remote also to see the same changes on your Heroku Application.

View Logs

To view logs, you can use the heroku logs --tail command. This streams logs as time-ordered events. ctrl C will stop streaming the logs.

heroku logs --tail

Define a Procfile

  • Procfile is a text file in the root directory of your app. It is used to explicitly declare what command should be used to run your application.
  • web: npm start can be added to your Procfile with a script for start in your package.json file
//Procfile
web: npm start

Add MongoDB URI

  • Open your application from your Dashboard.
  • Add your MongoDB URI to the Config Vars of your application found on the Settings page.
  • Set key same as what you've added to the .env file on your Backend and value as the URI.

image.png

Running the App Locally

To run the application locally, use heroku local web