Back to Blog
Node.jsHerokuDevOpsExpress

How to Deploy Node Express API to Heroku

August 8, 2022 2 min read Read on Medium

How to Deploy Node Express API to Heroku

So you've built an awesome API using Express with Node.js and now you want it to be public for any service or web application to use. Heroku is one of the simplest ways to deploy Node APIs to the cloud — no EC2 setup, no security groups, no SSH keys.

Prerequisites (MAC)

  1. Create a free Heroku account at https://signup.heroku.com/
  2. Install Node and NPM locally
  3. Install Heroku CLI tools via Homebrew:
brew tap heroku/brew && brew install heroku

Step 1: Create Local Node Express API

mkdir node-express-api-heroku cd node-express-api-heroku npm init -y touch index.js .gitignore npm install express cors

Step 2: Configure package.json

Include a start script and specify the Node engine version so Heroku knows what runtime to use:

[Code snippet available on Medium]

The key additions are the "start" script (Heroku looks for this specifically) and the "engines" field with your Node version.

Step 3: Add Routes to index.js

[Code snippet available on Medium]

A basic Express setup with CORS middleware and at least one route — Heroku will use whatever PORT environment variable it injects at runtime, so make sure you're reading from process.env.PORT.

Step 4: Initialize Git Repository

git init git add . git commit -m 'first commit message' git branch -M main

Step 5: Connect to Heroku Account

heroku login

This opens a browser window for authentication.

Step 6: Create Heroku Instance

heroku create

Heroku will generate a name for your app (e.g., fast-woodland-77884) and add a git remote called heroku.

Step 7: Push to Heroku

git push heroku main

Watch the build logs in your terminal. Heroku installs dependencies, detects the start script, and boots your app.

Step 8: Access Your API

Once deployed, Heroku provides a public URL like:

https://fast-woodland-77884.herokuapp.com/

Any subsequent git push heroku main will trigger a new deployment automatically.


Sources: