Skip Navigation
Show nav
Heroku Dev Center Dev Center
  • Get Started
  • Documentation
  • Changelog
  • Search
Heroku Dev Center Dev Center
  • Get Started
    • Node.js
    • Ruby on Rails
    • Ruby
    • Python
    • Java
    • PHP
    • Go
    • Scala
    • Clojure
    • .NET
  • Documentation
  • Changelog
  • More
    Additional Resources
    • Home
    • Elements
    • Products
    • Pricing
    • Careers
    • Help
    • Status
    • Events
    • Podcasts
    • Compliance Center
    Heroku Blog

    Heroku Blog

    Find out what's new with Heroku on our blog.

    Visit Blog
  • Log in or Sign up
View categories

Categories

  • Heroku Architecture
    • Compute (Dynos)
      • Dyno Management
      • Dyno Concepts
      • Dyno Behavior
      • Dyno Reference
      • Dyno Troubleshooting
    • Stacks (operating system images)
    • Networking & DNS
    • Platform Policies
    • Platform Principles
    • Buildpacks
  • Developer Tools
    • Command Line
    • Heroku VS Code Extension
  • Deployment
    • Deploying with Git
    • Deploying with Docker
    • Deployment Integrations
  • Continuous Delivery & Integration (Heroku Flow)
    • Continuous Integration
  • Language Support
    • Node.js
      • Working with Node.js
      • Node.js Behavior in Heroku
      • Troubleshooting Node.js Apps
    • Ruby
      • Rails Support
      • Working with Bundler
      • Working with Ruby
      • Ruby Behavior in Heroku
      • Troubleshooting Ruby Apps
    • Python
      • Working with Python
      • Background Jobs in Python
      • Python Behavior in Heroku
      • Working with Django
    • Java
      • Java Behavior in Heroku
      • Working with Java
      • Working with Maven
      • Working with Spring Boot
      • Troubleshooting Java Apps
    • PHP
      • PHP Behavior in Heroku
      • Working with PHP
    • Go
      • Go Dependency Management
    • Scala
    • Clojure
    • .NET
      • Working with .NET
  • Databases & Data Management
    • Heroku Postgres
      • Postgres Basics
      • Postgres Getting Started
      • Postgres Performance
      • Postgres Data Transfer & Preservation
      • Postgres Availability
      • Postgres Special Topics
      • Migrating to Heroku Postgres
    • Heroku Key-Value Store
    • Apache Kafka on Heroku
    • Other Data Stores
  • AI
    • Working with AI
    • Heroku Inference
      • AI Models
      • Heroku Inference Quick Start Guides
      • Inference API
      • Inference Essentials
    • Tool Use
    • Vector Database
    • AI Integrations
  • Monitoring & Metrics
    • Logging
  • App Performance
  • Add-ons
    • All Add-ons
  • Collaboration
  • Security
    • App Security
    • Identities & Authentication
      • Single Sign-on (SSO)
    • Private Spaces
      • Infrastructure Networking
    • Compliance
  • Heroku Enterprise
    • Enterprise Accounts
    • Enterprise Teams
  • Patterns & Best Practices
  • Extending Heroku
    • Platform API
    • App Webhooks
    • Heroku Labs
    • Building Add-ons
      • Add-on Development Tasks
      • Add-on APIs
      • Add-on Guidelines & Requirements
    • Building CLI Plugins
    • Developing Buildpacks
    • Dev Center
  • Accounts & Billing
  • Troubleshooting & Support
  • Integrating with Salesforce
    • Heroku AppLink
      • Getting Started with Heroku AppLink
      • Working with Heroku AppLink
      • Heroku AppLink Reference
    • Heroku Connect (Salesforce sync)
      • Heroku Connect Administration
      • Heroku Connect Reference
      • Heroku Connect Troubleshooting
    • Other Salesforce Integrations
  • Language Support
  • Node.js
  • Working with Node.js
  • Using WebSockets on Heroku with Node.js

Using WebSockets on Heroku with Node.js

English — 日本語に切り替える

Last updated September 05, 2025

Table of Contents

  • Setup a WebSocket-enabled App
  • Install Dependencies
  • Create the Server
  • Create a WebSocket Client
  • Start the App
  • Going Further

This tutorial gets you started with real-time Node.js applications on Heroku. We develop a simple application that shares the server’s current time with the client via a persistent socket connection. Each application is based on Node’s popular express web server.

When developing real-time Node.js applications, you can use WebSockets directly. You can also use an abstraction library like Socket.io, which provides fallbacks for clients that don’t support the WebSocket protocol. We demonstrate both options.

Using dynos to complete this tutorial counts towards your usage. We recommend using our low-cost plans to complete this tutorial. Eligible students can apply for platform credits through our new Heroku for GitHub Students program.

Setup a WebSocket-enabled App

Go to your app’s directory, and create a default package.json.

$ npm init --yes

Specify a version of Node in package.json, and provide a mechanism for starting the app.

"engines": {
  "node": "22.x"
},
"scripts": {
  "start": "node server.js"
}

Install Dependencies

Let’s start with a basic express web server.

$ npm install --save express

The simplest way to use WebSocket connections is with the ws module. For this, we install the ws, bufferutil, and utf-8-validate modules. Only the ws module is necessary, but the bufferutil and utf-8-validate modules provide a performance boost.

$ npm install --save ws bufferutil utf-8-validate

Create the Server

Add a file called server.js to the root of your app directory containing the following:

const express = require('express')
const { Server } = require('ws')

const PORT = process.env.PORT || 5001
const INDEX = '/index.html'

const server = express()
  .use((req, res) => res.sendFile(INDEX, { root: __dirname }))
  .listen(PORT, () => console.log(`Listening on ${PORT}`))

const wss = new Server({ server })

wss.on('connection', (ws) => {
  console.log('Client connected')
  ws.on('close', () => console.log('Client disconnected'))
});

setInterval(() => {
  wss.clients.forEach((client) => {
    client.send(new Date().toTimeString())
  })
}, 1000)

Accepting WebSocket Connections

To accept WebSocket connections, we need our HTTP server to do two things: - Serve our client-side assets. - Provide a hook for the WebSocket server to monitor for requests.

This is handled in server.js by these lines of code:

const PORT = process.env.PORT || 5001
const INDEX = '/index.html'

const server = express()
  .use((req, res) => res.sendFile(INDEX, { root: __dirname }))
  .listen(PORT, () => console.log(`Listening on ${PORT}`))

Then the WebSocket server must take our HTTP server as an argument so that it can listen for events. This is handled in server.js by these lines of code:

const { Server } = require('ws')

const wss = new Server({ server })

Finally, we listen for and log connections and disconnections. After a client connects, you can add event handlers for messages from that client. In server.js, this is handled by these lines of code:

wss.on('connection', (ws) => {
  console.log('Client connected')
  ws.on('close', () => console.log('Client disconnected'))
})

Broadcasting Updates

One of the benefits of socket connections is that your server can broadcast data to clients without waiting for client requests. For our example app, we push the current time to all clients every second using the following code from server.js:

setInterval(() => {
  wss.clients.forEach((client) => {
    client.send(new Date().toTimeString())
  });
}, 1000)

Create a WebSocket Client

Add a file called index.js to the root of your app directory containing the following:

<html>
  <head>
    <script>
      let HOST = location.origin.replace(/^http/, 'ws')
      let ws = new WebSocket(HOST);
      let el;

      ws.onmessage = (event) => {
        el = document.getElementById('server-time');
        el.innerHTML = 'Server time: ' + event.data;
      };
    </script>
  </head>
  <body>
    <p id="server-time"></p>
  </body>
</html>

This is a simple HTML page that listens for time updates from the server. It makes a connection to our WebSocket server, listens for broadcasted messages, and writes these messages to the page.

Start the App

You can now start the server.

$ npm start
> node server.js

Listening on 5001

Test the app locally at http://localhost:5001 to confirm that the time is updated in real time. You also see Client connected in your server logs.

When you’re satisfied with the behavior, commit all your files to git, except node_modules, which you want to add to .gitignore. Then deploy the app to Heroku.

$ heroku create
$ git commit -am 'websocket starting point'
$ git push heroku main
$ heroku open

Going Further

  • Using a library like Socket.io can make help your real-time applications more robust. It can fallback to methods like HTTP long-polling to serve users without WebSocket support, handle automatic reconnections, and provide advanced features like multiplexing and namespaced rooms.

  • When running real-time apps in clustered mode or when scaling to multiple dynos, you may want to enable session affinity:

    $ heroku features:enable http-session-affinity
    

    For Socket.io configuration, refer to the instructions at here.

Keep reading

  • Working with Node.js

Feedback

Log in to submit feedback.

Information & Support

  • Getting Started
  • Documentation
  • Changelog
  • Compliance Center
  • Training & Education
  • Blog
  • Support Channels
  • Status

Language Reference

  • Node.js
  • Ruby
  • Java
  • PHP
  • Python
  • Go
  • Scala
  • Clojure
  • .NET

Other Resources

  • Careers
  • Elements
  • Products
  • Pricing
  • RSS
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku Blog
    • Heroku News Blog
    • Heroku Engineering Blog
  • Twitter
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku
    • Heroku Status
  • Github
  • LinkedIn
  • © 2025 Salesforce, Inc. All rights reserved. Various trademarks held by their respective owners. Salesforce Tower, 415 Mission Street, 3rd Floor, San Francisco, CA 94105, United States
  • heroku.com
  • Legal
  • Terms of Service
  • Privacy Information
  • Responsible Disclosure
  • Trust
  • Contact
  • Cookie Preferences
  • Your Privacy Choices