DEV Community

Cover image for Hosting NodeJs Application on Heroku Platform using Heroku CLI
Altaf Shaikh
Altaf Shaikh

Posted on

Hosting NodeJs Application on Heroku Platform using Heroku CLI

In this blog, we will learn how to Host NodeJs Application on Heroku Platform using Heroku CLI. No need to leave your terminal or code editor, all from the terminal itself, huh?, pretty cool, right? Let's see how we can achive this.

Pre-requisite

Logging Into Heroku

Heroku login is required once. Enter below command in your terminal and follow up the prompt window and Authorize

heroku login
Enter fullscreen mode Exit fullscreen mode

Specify the version of node

Add The version of Node.js to your package.json file:

"engines": {
    "node": "10.x"  // replace x with your node version like 10.16.2
},
Enter fullscreen mode Exit fullscreen mode

Specifying a start script

create a Procfile file inside the root directory of the project and add the below code in it

web: node app.js
Enter fullscreen mode Exit fullscreen mode

By default, Heroku will look into our package.json file under the scripts section and grab start command. Sometimes we won't have that defined or it will be different from what we want the server to execute. We can specify the exact command we want by creating a Procfile file.

Create Heroku App and Remote Repository on Heroku

Specify a unique name for your application, this name should be globally unique.

heroku create <app-name>
Enter fullscreen mode Exit fullscreen mode

example:

heroku create todo-app-rest-backend-nodejs
Enter fullscreen mode Exit fullscreen mode

​Rename Your APP - Optional

If you got random app name or if you want to rename your Heroku app then use the below command to achieve it from the terminal itself.

heroku apps:rename <new-app-name> --app <old-app-name>
Enter fullscreen mode Exit fullscreen mode

​Build your app and run it locally - Optional

heroku local web
Enter fullscreen mode Exit fullscreen mode

Deploying Code To Heroku

git push heroku master
Enter fullscreen mode Exit fullscreen mode

Once the build and deployment is successful you will receive the url of the Hosted Application in your terminal.

If your Project has Environment Variables then Follow Below Along

Set a config variables on heroku app

Use below command for each environment variable to set all of your env variables and you are done.

heroku config:set <environment-variable-name>=<value>
Enter fullscreen mode Exit fullscreen mode

Examples:

heroku config:set GITHUB_USERNAME=joesmith
Enter fullscreen mode Exit fullscreen mode
heroku config:set PORT=3000
Enter fullscreen mode Exit fullscreen mode

Congratulations!! You had successfully learned how to host the NodeJS application on Heroku Like a PRO

Top comments (0)