Deploying Your Node.js App on Heroku: A Step-by-Step Guide
Introduction:
Are you looking to deploy your Node.js app on Heroku? In this post, we will go through the steps you need to follow to deploy your app successfully. By the end of this tutorial, you will have your Node.js app up and running on Heroku.
Step 1: Install the Heroku CLI
The first step to deploying your Node.js app on Heroku is to install the Heroku Command Line Interface (CLI) on your machine. The Heroku CLI is a command-line tool that lets you manage your Heroku apps directly from the terminal.
To install the Heroku CLI, open up your terminal and run the following command:
npm install -g heroku
This will install the Heroku CLI globally on your machine.
Step 2: Create a new Heroku app
Once the Heroku CLI is installed, you can create a new Heroku app by running the following command:
heroku create
This will create a new app on Heroku and give you a URL to access it. You can also specify a name for your app by running the following command:
heroku create my-awesome-app
Step 3: Add a Procfile
A Procfile
is a configuration file that tells Heroku how to start your app. It should be placed in the root directory of your project.
For a Node.js app, your Procfile
should contain the following line:
web: node index.js
This tells Heroku to start the app by running the index.js
file using Node.js.
Step 4: Commit your code to a git repository and push it to Heroku
Before deploying your app to Heroku, you must commit your code to a git repository and push it to Heroku.
To do this, run the following commands:
git init
git add .
git commit -m "Initial commit"
git push heroku master
This will push your code to the master
branch of your Heroku app.
Step 5: Set the Node.js version in your package.json file
In your package.json
file, you can specify the version of Node.js that your app is compatible with. Heroku uses this information to determine which version of Node.js to use to run your app.
For example, if your app is compatible with Node.js version 12, you can add the following line to your package.json
file:
"engines": {
"node": "12"
}
Step 6: Set up any environment variables
If your app requires any environment variables to run, you can set them up on Heroku by running the following command:
heroku config:set MY_ENV_VAR=value
Replace MY_ENV_VAR
with the name of your environment variable and value
with the value you want to set.
Step 7: Open your app in a browser
To open your app in a browser, run the following command:
Heroku open
This will open your app in a new browser window.
Conclusion:
Following these steps, you can quickly deploy your Node.js app on Heroku.
Done