0
0
ExpressHow-ToBeginner · 4 min read

How to Deploy Express App to Heroku: Step-by-Step Guide

To deploy an Express app to Heroku, first create a Procfile to tell Heroku how to run your app, then push your code to a Heroku Git remote using git push heroku main. Make sure your app listens on the port provided by process.env.PORT and has a start script in package.json.
📐

Syntax

Deploying Express to Heroku involves these key parts:

  • Procfile: A file that tells Heroku how to start your app.
  • package.json: Must include a start script to run your server.
  • Listening on the correct port: Your Express app must use process.env.PORT to work on Heroku.
  • Git commands: Use heroku create to make a Heroku app and git push heroku main to deploy.
bash
web: node index.js
💻

Example

This example shows a simple Express app setup ready for Heroku deployment. It listens on the port Heroku assigns and includes a Procfile and package.json with a start script.

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

const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello from Express on Heroku!');
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Output
Server running on port 3000 (or assigned Heroku port)
⚠️

Common Pitfalls

Common mistakes when deploying Express to Heroku include:

  • Not using process.env.PORT for the server port, causing the app to crash on Heroku.
  • Missing a start script in package.json, so Heroku doesn't know how to run the app.
  • Forgetting to commit the Procfile or having wrong syntax in it.
  • Not pushing to the correct Heroku Git remote branch.
javascript
Wrong (hardcoded port):
const PORT = 3000;

Right (dynamic port):
const PORT = process.env.PORT || 3000;
📊

Quick Reference

  • Create a Heroku app: heroku create
  • Add a Procfile with: web: node index.js
  • Ensure package.json has: "start": "node index.js" script
  • Use process.env.PORT in your Express app
  • Deploy with: git push heroku main

Key Takeaways

Always use process.env.PORT to listen on the correct port for Heroku.
Include a start script in package.json to tell Heroku how to run your app.
Create a Procfile with 'web: node index.js' to define the web process.
Use git push heroku main to deploy your code to Heroku.
Check for common mistakes like missing Procfile or hardcoded ports.