How to Deploy a NestJS Application to Heroku

Updated: January 1, 2024 By: Guest Contributor Post a comment

Overview

Deploying a NestJS application to Heroku can be streamlined with a step-by-step process. This guide provides instructions on how to prepare, build, and deploy your TypeScript-coded NestJS app onto the Heroku Cloud platform.

Prerequisites

  • A NestJS application
  • Heroku account
  • Heroku CLI installed
  • Git installed

The Main Process

Step 1: Prepare Your NestJS Application

Ensure your application follows the best practices for a production environment:

npm install --production

Modify the start script in your package.json to:

"scripts": {
    "start": "node dist/main",
    "prestart:prod": "npm run build"
}

Step 2: Configure Environment Variables

Set up your environment variables in Heroku instead of having them in a .env file:

heroku config:set NODE_ENV=production

Step 3: Set Up Git Repository

Initialize a Git repository in your project if you haven’t already:

git init
heroku git:remote -a your-app-name

Step 4: Create a Heroku Procfile

Create a file named Procfile in your project root without any extension and add the following line:

web: npm run start:prod

Step 5: Deploy Your Application

Commit your changes and push to Heroku:

git add .
git commit -m "Prepare for Heroku deployment"
git push heroku master

Heroku will detect your application, build it, and run npm start based on the Procfile

Advanced Configuration

Add TypeScript build pack for Heroku to compile your TypeScript code on deployment:

heroku buildpacks:add heroku/typescript

To scale your application:

heroku ps:scale web=1

To check the logs:

heroku logs --tail

Troubleshooting

Common issues while deploying cover Heroku limits, environment differences, or missing scripts. Ensure your application is listening on the port Heroku sets via process.env.PORT.

Ensuring Proper Build Processes

To enable proper build processes, including devDependencies during the build time:

heroku config:set NPM_CONFIG_PRODUCTION=false

Automating Deployments

Utilize GitHub integration to automatically deploy your reservations when you push to your repository:

heroku dashboard -> Deploy -> GitHub

Testing Deployments

To ensure deployments go smoothly, use Review Apps or Staging environments provided by Heroku.

Conclusion

Deploying your NestJS application to Heroku involves critical steps such as configuring environment variables, ensuring production-ready setups, and optimizing build configurations. Following these steps will bring your application to a globally accessible platform in a matter of minutes.