Using WebSockets on Heroku with Node.js
Last updated September 05, 2025
Table of Contents
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.