DEV Community

Leo Kalshteyn
Leo Kalshteyn

Posted on

Setting up Site with Heroku and Express.js

I recently read up on how to deploy a site or app to the web, as I have never done it before and thought about creating a brief guide on how to do it. As with most things, there are multiple ways but one of the simpler ways is running an Express server hosted on Heroku. Express is a Node.js framework for web apps and APIs and is used to help organize web apps into an MVC architecture on the server side. Heroku, on the other hand, is a cloud platform that supports a number of languages and frameworks including Node.js.

Setup

  • Node and npm installed on your local machine
  • Git installed
  • The Heroku CLI installed

Step 1: You must first initialize a Git repository to your project directory since Heroku relies on Git to deploy local code to the cloud.

Step 2: Then you login to the Heroku CLI and create a new project. You can either login through a web browser or through the CLI. You also need a free Heroku account.

CLI Login: $ heroku login -i

Step 3: Next, you initialize a new npm project by creating a package.json file.
Initializing: $ npm init -y. Then you install Express.

Step 4: The app.js is where the Express server will run locally and act as the entry point. First you require Express module and create an instance of the Express app. Next require the use of the express.static middleware from the directory you specify. After that, use app.get() to define a URL route. And finally add the port which Heroku will use, which will by default run on 3000 if run locally.

Example:

// create an express app
const express = require("express")
const app = express()

// use the express-static middleware
app.use(express.static("public"))

// define the first route
app.get("/", function (req, res) {
  res.send("<h1>Hello World!</h1>")
})

// start the server listening for requests
app.listen(process.env.PORT || 3000, 
    () => console.log("Server is running..."));
Enter fullscreen mode Exit fullscreen mode

Step 5: To deploy an app to Heroku requires a Procfile which basically tells Heroku which command to run to manage a given process. Here, the command will let your server listen to the web.
$ echo "web: node app.js" > Procfile

Step 6: Finally, add and commit all changes you do in your files and Git push them to Heroku master branch: $ git push heroku master

Heroku will build and deploy the app and notify when it is done in the command line.

References

Top comments (0)