changed 3 years ago
Linked with GitHub

How to Deploy Your Node.js App to Heroku


Set up

  • Do you have the prerequisites installed properly?
    • run the command node --version. You need any version of Node greater than 10.
    • run the command npm --version to make sure npm is there.
  • Create your Heroku account.
  • Install the Heroku CLI.
    • Use the heroku --version command to verify your CLI installation. The output looks like heroku/x.y.z.

Dependencies

  • If you haven't already created one, run npm init in the root directory of your app to create a package.json. When an app is deployed, Heroku reads the package.json to install the appropriate node version and the package-lock.json to install the dependencies.
  • To install dependencies, use npm install <pkg>. This will install the package and also add it as a dependency in the package.json file.

Procfile & PORT variable

  • To determine how to start your app, Heroku first looks for a Procfile. In the root directory of your app, create a file and name it Procfile (with no extensions). Use the Procfile to explicitly declare what command should be executed to start your app.
  • The Procfile in the app you deployed could look like this

    This command will use the start script that is specified in the package.json.
  • Make sure your PORT variable is assigned like this:
    const PORT = process.env.PORT || 5000;

Run locally

  • Start your app locally using the heroku local command. heroku local examines the Procfile to determine what to run.
    Your app should now be running on http://localhost:5000/.

Deploy the App

  • Make sure you have committed your changes to git.
  • Use the heroku login command to log in to the Heroku CLI.
  • Use heroku create to create your app on Heroku.
    Heroku generates a random name for your app. You can rename an app at any time by either
    • using the heroku apps:rename command:
      heroku apps:rename newname
      OR
    • by navigating to the Settings menu on your Heroku Dashboard

      If you rename your app via Dashboard, run the following commands to update the remote’s details in other repository instances
      git remote rm heroku
      heroku git:remote -a newname
  • Use git push heroku main to deploy your code.
  • Ensure that at least one instance of the app is running: heroku ps:scale web=1
  • Run heroku open to open the website
    You can use heroku logs --tail to view information about your running app and Control+C to stop streaming the logs.
Select a repo