Deploying an ExpressJS server on Heroku
Installing the Heroku CLI
This CLI will be useful deploying and monitoring your application directly from the command line.
The official documentation is quite good.
Getting Started
Ensure you have a Heroku account before proceeding. If you don’t, go ahead and make an account.
After you have your account ready, run the following command and login to your account.
heroku login
Creating your Heroku application
To run any application on Heroku, first you will need to create an application on Heroku. You can do this either through the CLI or through the Web UI. In this article, I will be using a sample real time chat project I’d developed called Chatter. I want this to be accessible at the link:
https://chatter-sharad.herokuapp.com
So, we need to do the following,
heroku create chatter-sharad --buildpack heroku/nodejs
Add the remote Heroku git repo.
heroku git:remote -a chatter-sharad
Create your ExpressJS application. Heroku will use the package.json
file to read and install required packages. Therefore, ensure it is in the root folder, otherwise the deployment will fail.
Creating a Procfile
For Heroku to know which command should be run, we need to define a Procfile
and add the following line.
web: npm start
This will run the npm start
command after the build is successful.
Configuration Variables
Add any required config vars (env vars) using the following command.
heroku config:set key=value -a <app-name>
Pushing and Deploying
Push the local changes to the Heroku main
branch.
git push heroku main
As soon as you push the changes, Heroku will start to build your application.
After the build is successful, the app gets deployed. You can then head over to the link: https://app-name.herokuapp.com
Since our app was called chatter-sharad
, the application will be visible at:
Resources
- Heroku CLI — https://devcenter.heroku.com/articles/heroku-cli
- Heroku NodeJS Deployment — https://devcenter.heroku.com/articles/getting-started-with-nodejs
- My Git Repo — https://github.com/sharadbhat/Chatter