Deploying Express.js Apps to Heroku

Tutorial 1 of 5

Introduction

This tutorial aims to guide you through deploying your Express.js applications to Heroku, a cloud platform service that supports several programming languages. By the end of this tutorial, you will have a working Express.js application deployed on Heroku.

You will learn:
- Setting up your Heroku account
- Preparing your Express.js application for deployment
- Deploying your application to Heroku

Prerequisites:
- Basic knowledge of JavaScript and Express.js
- A working Express.js application
- Git installed on your local machine

Step-by-Step Guide

1. Setup your Heroku Account

  • First, visit Heroku.com and sign up for a free account if you don’t have one yet.

2. Install the Heroku CLI

  • Download and install the Heroku Command Line Interface (CLI) from here. The Heroku CLI is a tool that allows you manage your apps directly from the terminal.

3. Log in to Heroku

  • After installing the CLI, open your terminal and log in to Heroku by typing heroku login. You will be prompted to enter your Heroku credentials.

4. Prepare your Express.js Application

  • In your application directory, initialize a Git repository by running git init.
  • Create a file named .gitignore and add node_modules/ to it. This prevents Git from tracking unnecessary files.

5. Deploy your Application

  • Commit your changes with git add . and git commit -m "First commit".
  • Create a new Heroku app by running heroku create your-app-name. Replace your-app-name with the name you want for your app.
  • Push your code to Heroku with git push heroku master.

Code Examples

Creating a simple Express.js app:

const express = require('express');
const app = express();

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

app.listen(process.env.PORT || 5000, function () {
  console.log('Express app is running!');
});
  • const express = require('express'): This line imports the Express.js module.
  • const app = express(): This line creates an instance of Express.
  • app.get(...): This sets up a route that handles HTTP GET requests.
  • app.listen(...): This tells the app to listen for incoming requests on a specific port.

Summary

You've learned how to deploy an Express.js app to Heroku. You've set up your Heroku account, prepared your app for deployment, and pushed your app to Heroku.

Practice Exercises

  1. Create a new Express.js app and deploy it to Heroku.
  2. Add another route to your app and deploy the changes to Heroku.
  3. Modify your Express app to serve static files and deploy the changes to Heroku.

Remember to commit and push your changes to Heroku after each modification.

Additional Resources

Happy coding!