How to use Socket.io with PM2 process manager?

How to use Socket.io with PM2 process manager?

Socket.io with PM2

As we know, PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, reload them without downtime, and facilitate common system admin tasks.

To convert any basic socket.io application, we need to change a couple of things in both client & server-side codes. In this article, we'll see how we can achieve this.

To demonstrate this I'll use one of my "real-time group chat application" whose Github link is - github.com/mi6crazyheart/chat-server-for-re... I've already written a full article on how to use this here - byteblocks.hashnode.dev/how-to-create-a-cha..

Let's start with client-side file changes. In file client/assets/js/app.js we need to pass additional two parameters transport & withCredentials -

var socket = io('http://localhost:8080', {
    transports: ["websocket"],
    withCredentials: true
});

By passing parameter transports: ["websocket"] we are disabling HTTP long-polling on the client-side. withCredentials: true is getting used for making cross-site requests using credentials such as cookies, authorization headers or TLS client certificates.

Now in Server-Side(server/server.js), we need to following changes -

  • enable sticky sessions, so that the HTTP requests of a Socket.IO session are routed to the same worker. To do this we need to install
    npm install @socket.io/sticky
    
  • use a custom adapter, so that the packets are broadcast to all clients, even if they are connected to another worker. To do this we need to install
    npm install @socket.io/cluster-adapter
    

To use both the sticky header & custom adapter in our code we need to include them by using these lines -

const { createAdapter } = require("@socket.io/cluster-adapter");
const { setupWorker } = require("@socket.io/sticky");

Inside CORS setting we need to pass

credentials: true

Again, to use both the sticker header & custom adapter functionality we need to add the following two lines after creating the io variable.

io.adapter(createAdapter());
setupWorker(io);

After doing all these modifications, we've to use a socket.io based PM2 library rather than using the official one by installing. You can get more info from here - socket.io/docs/v4/pm2/#installation

npm install -g @socket.io/pm2

That's it. Now we can start our PM2 demon by using the following command. PM2 will use all your processor cores by spinning that many processes.

pm2 start server.js -i 0

You can get all the updated codes from this Github link - github.com/mi6crazyheart/socketio-with-pm2

Also, check this official docs for more in-depth info: socket.io/docs/v4/pm2

For any kind of queries, you can comment down. I'll try to answer them one by one.

To know more about such development information, follow me @ -