Deploy Nodejs application on Heroku

Deploying nodejs application on Heroku cloud

This blog article assumes the following directory structure:

- client\
- server\
    - src
      - index.js
    - package.json
- .git\
- README.md

You can follow this documentation to deploy nodejs application on heroku cloud.

Prerequisites

package.json is a starting point for the deployment. Heroku requires the application being deployment to have the package.json file in the root.

  • Even if you dont have nodejs related code in the root, you can just deploy the directory (server) where the nodejs code resides within your actual repo.

Also, you need to specify the nodejs version you would be using in the server\src\package.json file:

"engines": {
  "node": "14.x"
}

Also, within the script tag requires a "start" script.

Javascript based nodejs app

"scripts": {
  "start": "node src/index.js"
}

Typescript based nodejs app

"scripts": {
  "start": "ts-node src/index.ts"
}

Setup Heroku App

Login to heroku cloud from https://dashboard.heroku.com.

Create a new app in https://dashboard.heroku.com/apps.

Setting up Heroku CLI

Heroku gives you multiple options of how you can supply your application source code.

img

Here we are gonna discuss doing deployment using the Heroku CLI. To setup the heroku CLI, follow steps here:

https://devcenter.heroku.com/articles/heroku-command-line

Create git repo

Even though your actual code might be in github, you can follow the following steps. Heroku requires your code to be added to a git repo within heroku cloud. Heroku then uses this repo to do the deployment.

img

So in order for us to do the deployment, we need to execute the following commands.

heroku login

cd fantastic-app/server
git init
heroku git:remote -a fantastic-app

The above commands will initialize the heroku CLI using your heroku account credentials. And then we initialize the server codebase as a git repo and link it to the heroku git.

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

Now we commit and push our server code to heroku. The git push heroku master command pushes the code to heroku. Heroku looks for package.json and within that it uses the start script to deploy your nodejs application.

Let me know if you ran into any issues following the above steps, I will help you get your deployment done.