Host a Node.js API on Heroku
Sometimes there is a need to set up a Node.js API to test out an idea. Heroku offers the possibility of doing so but by default, it assumes that there’s a web process in the deployment. Here’s how to work around that so that this can happen:
(Wanna get straight to the code? https://github.com/YFLooi/task-list-app-backend)
First, let’s set up an Express backend. Install the following packages:
yarn add express cors dotenv
yarn add --dev cross-env
cross-env enables using bash-style env variables in the package.json start script.
Set up a repo (e.g. “npm init”). In package.json, include the following lines:
{
...
"main": "server.js",
...
"engines": {
"npm": "6.4.1",
"node": "14.15.3"
},
...
"scripts": {
"start": "cross-env PORT=$PORT node server.js"
"heroku-postbuild": "npm install",
"test": "echo \"Error: no test specified\" && exit 1"
},
...
}
Notice the “start” script? “$PORT” is attached by Heroku’s HTTP routing stack when the deployed app loads (ref in Heroku docs). This ensures calls to “https://appName.herokuapp.com/” can be received by the Nodejs API.
To ensure this “start” script runs on load, declare the following Procfile at the root of the repo:
web: node server.js
The weird name is because Heroku expects a “web” process, hence the Nodejs API has to be declared this way.
Now to set up server.js in the root of the repo. Let’s do a simpler version of the one in the example Github repo that returns some JSON:
const express = require(“express”);const server = express();
const port = process.env.PORT || 3500;
const cors = require("cors");
require("dotenv").config();server.use(cors());server.get(`/`, async (req, res) => {
console.log(`Call made to root route at “/”. Returning json`);
res.json({"message":"You have contacted your Nodejs API on Heroku!"});
});server.listen(port, () => {
console.log(`Server is listening on http://localhost:${port}`);
});
Time to deploy. I’ m going to refer to the Heroku CLI in this example (download here).
Head to your Heroku account to create a new app. Copy the Heroku Git url to your app, you’ll find it here under the app’s “Settings”:
Add this Git url to the repo’s Git remote:
git remote add heroku https://git.heroku.com/your-heroku-app.git
Log into your Heroku account from the command line using “heroku login”. You’ll be redirected to a browser to insert your credentials.
Now that you are logged in, deploy by running the following:
git push heroku master
Once the process is complete, spin up the web process with:
heroku ps:scale web=1
Go to your Heroku account dashboard. Click on “Open App” then copy the resulting url in your browser. It looks something like “https://your-heroku-app.herokuapp.com/”
Now to check if your Node.js API is up and running. Using Postman, set up a a GET request. Here’s as an example:
Click “Send”. If all is well, the response would return:
{"message":"You have contacted your Nodejs API on Heroku!"}