Deploy Node.js app on heroku

Signup/Signin on heorku

https://herokuapp.com/

Login from terminal (Make sure you have installed heroku cli – https://devcenter.heroku.com/articles/heroku-cli#download-and-install)

heroku login

Create app.js

const express = require("express");
const app = express();
const port = 8080;

app.get("/", (req, res) => {
    res.send("Hello Heroku");
})

app.listen(process.env.PORT || port, () => {
	console.log("listening 8080...");
});

process.env.PORT this will be provided by heroku server

Test locally by running following command

node app.js
OR
nodemon app.js

If you get any error e.g. module not found you can install those module using npm

npm install <module_name>

To find installed module version

npm view <module_name> version
e.g.
npm view express version

Create package.json

{
	"scripts" : {
		"start" : "node app.js"
	},
	"dependencies": {
		"express": "4.17.1",
		"mongoose": "5.13.3",
		"cors": "2.8.5"
	}
}

Run following command from terminal

#onetime
git init
#onetime
heroku create <yournewappname>

Run git commands

git add .
git commit -m 'msg'

#to verify origin
git config -l

#if you are not able to see url and fetch then run git remote add origin 
#remote.heroku.url=https://git.heroku.com/project.git
#remote.heroku.fetch=+refs/heads/*:refs/remotes/heroku/*
#git remote add origin heroku_git_url
#git push origin master

git push heroku master

Once app is deployed it will show you an url which you can access publicly from internet.

To see error logs

heroku logs --tail

4 Replies to “Deploy Node.js app on heroku”

    1. you need to install git first if you are using windows you can search for git for windows on google and download git

  1. after “git push origin master” command it is showing an error
    error: failed to push some refs to ‘https://git.heroku.com/pehlibaartest.git’

  2. Push rejected, failed to compile Node.js app.
    remote:
    remote: ! Push failed
    remote: !
    remote: ! ## Warning – The same version of this code has already been built: 3dd7c9c443d6c4ba0a778c312054d49b3d1f28d1
    remote: !
    remote: ! We have detected that you have triggered a build from source code with version 3dd7c9c443d6c4ba0a778c312054d49b3d1f28d1
    remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
    remote: !
    remote: ! If you are developing on a branch and deploying via git you must run:
    remote: !
    remote: ! git push heroku :main
    remote: !
    remote: ! This article goes into details on the behavior:
    remote: ! https://devcenter.heroku.com/articles/duplicate-build-version
    remote:
    remote: Verifying deploy…
    remote:
    remote: ! Push rejected to anandsem6.

    How To Fix This

Leave a Reply

Your email address will not be published. Required fields are marked *