In today's tutorial, we are going to build an URL shortner app and deploy it to Heroku. To make the development process easier we'll be using lightweight web framework Express.

Prerequisites

* Git installed, and configured on your machine

Git is a version controlling system that tracks each and every change you did you to files in a project. It keeps records on what the changes were did to files (what was added? what was removed), who made the changes, notes and comments about the changes by the changer and also it keeps records on the time which the changes happened.

* Heroku account and Heroku CLI installed, and configured on your machine

If you haven't a Heroku account, you can obtain a account from here. To install install Heroku CLI on your machine follow the steps given here.

Create project directory

Before moving into coding part, you need to create a project directory for our application. Let's cd into the workspace and create a new directory for the project:
1
mkdir url-shortener

Initializing npm

Next let's initialize npm, and with it, start our project:
1
npm init

npm init will ask a series of questions like package name, version, description, etc. Node will then generate a package.json file and print it to the terminal or you can simply skip this by running npm init -y. Then we need to add "start": "node app.js" to "scripts" section. This will be extremely important later, when we deploy the app to Heroku.

1
2
3
4
5
6
7
8
9
10
11
12
{
"name": "url-shortener",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
}

Installing Dependencies

1
npm install express body-parser --save

Building a Node Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const express = require('express');
const bodyParser = require('body-parser');
const urlShortener = require('node-url-shortener');
const app = express();
const path = require('path');
const port = process.env.PORT || 3000;


app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded());

app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});

app.post('/url', function (req, res) {
const url = req.body.url;

urlShortener.short(url, function (err, shortUrl) {
res.send(shortUrl);
});
});

app.listen(port, () => console.log(`url-shortener listening on port ${port}!`));

Create index.html

Then you need to create a index.html in your root directory.
1
2
3
4
5
6
<h1>URL Shortener</h1>

<form method="POST" action="/url">
<input type="text" name="url" />
<input type="submit" />
</form>
We can test if the application is running by executing below command:
1
node app.js

and navigate to http://localhost:3000

Handling Form Submission

To handle form submission, add below code to your app.js:
1
2
3
4
5
...
const bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.urlencoded());

then you need to add below code to app.js

1
2
3
4
5
app.post('/url', function(req, res) {
const url = req.body.url;

res.send(url);
});

Shortening the URL

For Shortening the URL, we can use the node-url-shortener module. Then require the package in the application:
1
const urlShortener = require('node-url-shortener');

And finally, we should add another block of code that shortens the URL before sending it back:

1
2
3
4
5
6
7
app.post('/url', function (req, res) {
const url = req.body.url;

urlShortener.short(url, function (err, shortUrl) {
res.send(shortUrl);
});
});

Pushing to Heroku

First you need to log in to to your Heroku account using Heroku CLI. To it running below command in your terminal:
1
heroku login

We are going to deploy our app to Heroku via Git. This is a new project, Git needs to be initialized:

1
git init

Now, we have already initialized our project, now we need to commit all the project files:

1
git commit -m "first commit"

Note:

Before commit your files, make sure to add your node_modules to .gitignore file.

Once the project is commited, we need to create a Heroku app for our Node app:
1
heroku create

This command returns the newly created app name and URL (your app name will be different to mine). If you browse to the URL you’ll see a Heroku welcome page.

Deploying the App

We have already create an app for our application and now, we are in our final step. To deploy our app to Heroku, run below command in your terminal:
1
git push heroku master

If the application is successfully deployed, we can go ahead and start it up.

Conclusion

In this tutorial, we obtain how can we deploy a Node.js application to Heroku. You can obtain complete source code for this tutorial from this GitHub repository.

Happy Coding