Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Deployment and Hosting (e.g., Heroku)

Deployment and Hosting (e.g., Heroku)

Deploying and hosting a Node.js application involves making it accessible on the internet so that users can access it. One popular platform for hosting Node.js applications is Heroku. Here's a step-by-step guide on how to deploy a Node.js application on Heroku:

Step 1: Set Up Your Node.js Application

Ensure your Node.js application is ready for deployment. This includes having a package.json file with necessary dependencies and a main script (usually app.js or index.js).

Step 2: Create a Git Repository

If you haven't already, initialize a Git repository for your project:

git init
 
Add and commit your project files:

git add .
git commit -m "Initial commit"
 

Step 3: Install Heroku CLI

Install the Heroku Command Line Interface (CLI) which allows you to interact with Heroku services from the command line.

Follow the instructions on the Heroku CLI installation page for your operating system.

Step 4: Log in to Heroku

Open a terminal and log in to your Heroku account:

heroku login
 

Step 5: Create a Heroku App

Create a new Heroku app using the Heroku CLI:

heroku create your-app-name
 
Replace your-app-name with a unique name for your app. If you omit the name, Heroku will generate a random one for you.
 

Step 6: Add a Start Script

In your package.json file, make sure you have a start script that specifies the command to start your application. For example:

Install the ws (WebSocket) library:

"scripts": {
  "start": "node app.js",
  ...
}
 

Step 7: Set the Port

In your Node.js application, ensure you're using the process.env.PORT variable to listen on the correct port. Heroku dynamically assigns a port number.

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
 

Step 8: Add a .gitignore File

Create a .gitignore file and add any files or directories that should not be included in your Git repository (e.g., node_modules, .env).

Step 9: Commit Changes

Commit any changes you've made to your Git repository:

git add .
git commit -m "Prepare for Heroku deployment"
 

Step 10: Deploy to Heroku

Deploy your application to Heroku:

git push heroku master
 

Step 11: Open Your App

Once the deployment is complete, you can open your app in the browser using:

heroku open
 

Your Node.js application is now hosted on Heroku and accessible via the provided URL.

Additional Tips:

  • To view logs of your application on Heroku, use the command heroku logs --tail.
  • If you need to make changes and redeploy, commit your changes and push to Heroku again:
git add .
git commit -m "Update something"
git push heroku master