Introduction: How to Deploy a Node.js App on Heroku
Step 1: Create a Package.json
Introduction:
Heroku is ahosting website that allows ypu to deploy 5 apps for free with a runtime of 500+ hours per month. To deploy one, you'll need to upload 3 files:
- A package.json and package-lock.json flle. You can follow my other tutorial for a step by step turtorial on making one by clicking here. The package-lock.json shows up automatically after a package.json is made. Since we will be running it on herku, on your package,json file you need to specifiy a start script and the verison of your node on enines. to now this run the command node -v. Here's an example:
{"name": "heroku",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js "
},
"keywords": [],
"author": "",
"license": "ISC",
"engines": {
"node": "12.x"
}
}
Step 2: Create Your Node.js App
Since this app will run on any port heroku give us, we need to determine the code it will gives us by using this code process.env.PORT . Here's a node js app that says "hello":
const http = require('http'); //loads the library to enable it to act as a server
var port = process.env.PORT || 5000; //specifies the port no to whatever heroku gives or 5000 on local host http.createServer(function(req,res){ // creates a server res.writeHead(200,{'Content-type':'text/plain'}); //Specifies that the respones "hello" is a text res.end("hello"); //shows the text "hello" on th eweb page }).listen(port); // attaches this server to the port no.
Step 3: Command Prompt
- Open your command prompt by pressing Windows+R to open “Run” box then type “cmd” and then click “OK”
On you CMD, go to the root by typing "cd .." until no path is include.
- Check if npm(a library manager installed by node), git and heroku is properly installed by typing:
npm --version git --version heroku --version
- Login in to yor herku account.
heroku login
- This create an app on heroku:
heroku create <app-name-of-your-choice>
- To upload your files, you need to got to its path by typing cd <path>
cd <your-path>
- Creates a new repository(folder) on your locl device for the items in this path
git init
- Connect remotely to a folder on heroku via git on your app
heroku git:remote <app-name-of-your-choice>
- Copies this file remotely to your local git repository u via git on your app
git add .
- Save the changes you've done on the folder with a message of "make it better"
git commit -am "make it better"
- Uploads the files to the git folder on heroku. Wait for it to downlaod
git push heroku master
- opens the app
heroku open app