Build and deploy a node express server to Heroku in 10 steps.

Grant Spilsbury
2 min readDec 13, 2017

--

I’ll be using a Mac Mini with Mac OS HighSierra and SublimeText 3 as my text editor. You’ll also need a free Heroku account and Heroku CLI installed. Also, make sure node.js is installed.

Step 1
Create a new demo directory and open it

// in terminal
$ mkdir demo
$ cd demo

Step 2
Initialise your node project. This will add a package.json file to your directory. The -fy flags sets the project details (author etc) for you. You can run the command without -fy(eg npm init) if you don’t want the defaults.

// in terminal
demo$ npm init -fy

Step 3
Add express via npm. The — save flag adds the dependency to your package.json file.

// in terminal
demo$ npm i express --save

Step 4
Add a app.js file. You can also open your project and create this file manually.

// in terminal
demo$ touch app.js

Step 5
Open your project in sublime (or your favourite text editor).

// in terminal… this will only work if you’ve set up a shortcut to sublime.
demo$ subl .

Step 6
Update your `package.json` file to include a start script and change the "main" property to app.js.

// in sublime
{
“name”: “demo”,
“version”: “1.0.0”,
“description”: “”,
“main”: “app.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1",
“start”: “node app.js”
},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“express”: “⁴.16.2”
}
}

Step 7
Add the following to the app.js file. This sets up your server to listen on a specific port and tells node to use express to help with routing. This also tells your server to respond with {Hello:”world"} whenever someone visits your home page.

// in sublime
var express = require(‘express’);
var port = process.env.PORT || 3000;
var app = express();app.get(‘/’, function (req, res) {
res.send(JSON.stringify({ Hello: ‘World’}));
});
app.listen(port, function () {
console.log(`Example app listening on port !`);
});

Save your work, close sublime, and open your terminal. Make sure you’re still in the same directory.

Step 8
Initialise a git repo and commit your work.

// in terminal
demo$ git init
demo$ git add -a -m “Initial commit”

Step 9
Log in, create an app, and push your work to Heroku.

// in terminal
demo$ heroku login
// follow prompts to enter your Heroku login credentials
demo$ heroku create
// you should see your server’s url after this has finished.
demo$ git push heroku master

Step 10
Open your brand new web server on your favourite browser.

// in terminal
demo$ heroku open

Step 11

// Sit back and marvel at your node.js development and deployment.

--

--