Step 9

We must make two changes to our repository for Heroku to successfully deploy our server application.

First, we must add a Procfile to the root of the repository with the following content

web: node ./server.js

A Procfile specifies the commands that are executed by the Heroku app on startup. Read more about it here.

Next, we must update the server.js as follows. Change this line

  const http = require("http");
  const fs = require("fs");
+ const port = process.env.PORT || 7000;
  const file = fs.readFileSync("./index.html", "utf8");

  const server = http.createServer((request, response) => {
    response.writeHead(200, { "Content-Type": "text/html" });
    response.write(file);
    response.end();
  });

- server.listen(7000);
+ server.listen(port);
- console.log("Listening! (port 7000)");
+ console.log(`Listening! (port ${port})`);

The process.env.PORT || 7000 says assign the environment variable PORT as the port number, or 7000 if PORT is not defined. We need this change because Heroku will automatically assign a port to your application. It then stores the port number as an environment variable, PORT. We cannot tell Heroku which port to use! We must use what it assigns to our application.

Finally, open the terminal and run the following command at the root of the project.

npm init -y

The command will create a package.json file inside the root folder. By convention, every Node application (package) has a package.json file at its root folder. We have seen this file before inside React applications. Recall this file holds metadata relevant to the project. It is also used, by NPM, for managing the project's dependencies, scripts, version and a whole lot more.

Now commit and push your changes. As the new changes get to your GitHub repository, Heroku will build and deploy the server application. Give it a minute or two, and then visit your Heroku App.

My server is deployed at https://bmi-calculator-fa21.herokuapp.com/.