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.
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.