How to host your Node API on Heroku using your Git Repository

How to host your Node API on Heroku using your Git Repository

There are several ways to host your Node API on Heroku. A common method is using the Heroku CLI which can get complicated especially for a beginner.

But did you know, you can host your app without even downloading the CLI.

I know right?

All you need is a GitHub repository that contains your code and a Heroku account which makes hosting quite easier and faster.

Follow the steps below on how to go about this.

1. Push your code to a Github Repository

To get started, you need to create a Github account and create a repository for you to push your code to. However, before you push, there are three things you need to ensure your code contains in order for your app to seamlessly run on Heroku

  • Set your environment variable: While building your app using express, you are required to set a PORT number that the app listens to. For your code to run successfully on Heroku, you have to set the PORT to an environment variable by doing the following:

First, install the package dotenv: npm install.PNG

Then create a .env file in the root directory of your project and set your port number to what you want to use in your application: env file.PNG

In your index.js/app.js, import the PORT variable by: index.PNG

Your application will run on port 6000 locally but will use the environment variable on Heroku.

  • Edit your package.json file: In your package.json file, you need to set a command that will start your app on Heroku like this: json file.PNG
  • Create a Procfile in the root directory of your project: Please note your Procfile should have no extension (e.g "Procfile.txt" or "Procfile.js" is not valid). This file sets the dynos settings for your project. Once created, state how your file should be called by using either of the following: proc.PNG

Once all three above have been done, push your code to GitHub.

2. Create an app on Heroku

Create a free account on Heroku and sign up. Once you are logged in to your dashboard, click on the "New" button to create a new app. Input your preferred app name and set a region. Once this is done, go to the deployment section and connect to GitHub heroku-git.PNG

Follow the next steps which will lead to viewing all your repositories on GitHub, select the repository your code was pushed on, and deploy to the main branch. I would advise you to enable automatic deploys so that any new commits pushed to the main branch of your repository will be automatically reflected on Heroku. deploys.PNG

3. One last thing, set your environment variables on Heroku

Click on the settings tab of your Heroku app, go to Reveal Config Vars, Add the variables from the .env file as key-value pairs to the Config Vars of your app

All set, there you go, your app should be up and running.

Got any questions? feel free to drop in the comments below