Skip to main content

Using WebSockets on Heroku with Node.js

Table of Contents

  • Create a new app
  • Option 1: WebSocket
  • Option 2: Socket.io

This tutorial will get you going with realtime Node.js applications on Heroku. We’ll develop a simple application that shares the server’s current time with the client via a persistent socket connection. Each application will be based on Node’s popular express web server.

When developing realtime Node.js applications, you can directly use WebSockets, or you can use an abstraction library like Socket.io which provides fallbacks for clients that don’t support the WebSocket protocol. We’ll demonstrate both options below.

Create a new app

Move into your app’s directory and create a default package.json:

$ npm init --yes

Let’s also specify a version of Node in package.json and provide a mechanism for starting the app:

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

Option 1: WebSocket

The simplest way to use WebSocket connections is directly through Node’s ws module. We’ll walk through each step in setting up the app, but you can view the full source on GitHub.

Install dependencies

Let’s start with a basic express web server:

$ npm install --save express

For WebSockets, we’ll install the ws module as well as bufferutil and utf-8-validate. Only the wsmodule is necessary, but the bufferutil and utf-8-validate modules provide a performance boost.

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

Create an HTTP server

We need an HTTP server to do two things: serve our client-side assets and provide a hook for the WebSocket server to monitor for requests. The server code will look like this:

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

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

Create a WebSocket server

The WebSocket server takes an HTTP server as an argument so that it can listen for events:

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

const wss = new Server({ server });

Handle connections

Here, we’ll listen for and log connections and disconnections. Once a client has connected, you can also add event handlers for messages from that client. The server code looks like this:

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

Broadcast updates

One of the benefits of socket connections is that your server can broadcast data to clients without waiting for client requests. In this case, we’ll push the current time to all clients every second:

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

Create a WebSocket client

Our client, index.html, is a simple HTML page that listens for time updates from the server. The client code can go between <script> tags in the HTML and looks like this:

var HOST = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(HOST);
var el;

ws.onmessage = function (event) {
  el = document.getElementById('server-time');
  el.innerHTML = 'Server time: ' + event.data;
};

Start the app

You can now start the server:

$ npm start
> node server.js

Listening on 3000

Test the app locally at http://localhost:3000 to confirm the time is being updated in realtime. You will also see Client connected in your server logs.

Once you’re satisfied with the behavior, commit all your files to git (except node_modules, which should be added to .gitignore) and deploy the app to Heroku:

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

Option 2: Socket.io

A realtime abstraction library like Socket.io can help your app serve users without WebSocket support. Socket.io also provides common functionality like rooms, namespaces, and automatic reconnection. We’ll walk through each step in setting up the app, but you can view the full source on GitHub.

Install dependencies

This app requires a basic express web server as well as socket.io:

$ npm install --save express socket.io

Create an HTTP server

We need an HTTP server to do two things: serve our client-side assets and provide a hook for Socket.io to monitor for socket.io-related requests. The server code looks like this:

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

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

Create a Socket.io server

The Socket.io server takes an HTTP server as an argument so that it can listen for socket.io-related requests:

const io = socketIO(server);

Handle connections

We’ll log clients connecting and disconnecting. Once a client has connected, you can also add event handlers to the SocketIO instance for receiving client messages.

io.on('connection', (socket) => {
  console.log('Client connected');
  socket.on('disconnect', () => console.log('Client disconnected'));
});

Broadcast updates

One of the benefits of persistent socket connections is that the server can push data out to clients without waiting for a client’s request. In this example, we’ll push the current time on the server once per second:

setInterval(() => io.emit('time', new Date().toTimeString()), 1000);

Create a Socket.io client

Our client, index.html, is a HTML simple page that listens for time updates from the server. The client code can go between <script> tags in the HTML and looks like this:

var socket = io();
var el;

socket.on('time', function(timeString) {
  el = document.getElementById('server-time')
  el.innerHTML = 'Server time: ' + timeString;
});

Start the app

You can now start the server:

$ npm start
> node server.js

Listening on 3000

Test the app locally at http://localhost:3000 to confirm the time is being updated in realtime. You will also see Client connected in your server logs.

Once you’re satisfied with the behavior, commit all your files to git (with node_modules in .gitignore) and deploy the app to Heroku.

$ heroku create
$ git commit -am 'socket.io starting point'
$ git push heroku master
$ heroku open

Apps using Socket.io should enable session affinity. If you plan to use Node’s Cluster module or to scale your app to multiple dynos, you should also follow Socket.io’s multiple-nodes instructions.

$ heroku features:enable http-session-affinity

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...