Skip to main content

Deployment to Heroku

Introduction

Heroku is a popular platform for hosting applications in various programming languages, including Node.js. This tutorial will guide you through the process of deploying your Node.js application to Heroku.

Prerequisites

Before we begin, you'll need to have the following:

  • A basic understanding of Node.js
  • Node.js and NPM installed on your local machine
  • A Heroku account (It's free to sign up)

Step 1: Setting up Your Node.js Application

If you already have a Node.js application to deploy, you can skip this step. Otherwise, let's quickly create a simple Node.js application.

In your terminal, create a new directory for your application, navigate into it and then initialize a new Node.js application:

mkdir my-app
cd my-app
npm init -y

Now, let's install express, a popular Node.js framework, and create a basic server:

npm install express

Create a new file named index.js and add the following code:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
res.send('Hello World!');
});

app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});

Step 2: Preparing Your Application for Heroku

Heroku needs a Procfile to know how to run your application. In the root directory of your application, create a new file named Procfile (no file extension) and add the following line:

web: node index.js

Heroku also needs to know the versions of Node.js and NPM that your application requires. You can specify this in your package.json file:

"engines": {
"node": "14.x",
"npm": "6.x"
}

Step 3: Deploying Your Application to Heroku

First, you need to install the Heroku CLI. Follow the instructions here to install it on your machine.

After installing the Heroku CLI, open your terminal, navigate to your application directory, and log in to Heroku:

heroku login

Next, create a new Heroku application:

heroku create

Now, you're ready to deploy your application. Commit your changes if you haven't done so yet, and then push your application to Heroku:

git init
git add .
git commit -m "Initial commit"
git push heroku master

Step 4: Opening Your Application

If everything went well, your application should now be live on Heroku. You can open it in your web browser with the following command:

heroku open

And that's it! You've successfully deployed your Node.js application to Heroku.

Conclusion

Deploying a Node.js application to Heroku is a straightforward process. By following these steps, you can make your application accessible to the world. Happy coding!