Is it okay to store ws clients in an array in NodeJS?

3.9k Views Asked by At

I'm using the ws library so WebSockets implementation. In this, to broadcast, the GitHub page has a sample code that does a forEach on wss.clients and sends data to everyone of the clients.

But, I don't like the idea of storing clients, an important set of data, in an array that can be destroyed by a simple server restart.

Is there a way to store the clients somewhere more persistent, like Redis. So, I store the metadata of clients in Redis and create the client on the go from Redis as required.

Or is this Redis a bad approach and arrays are just good enough?

Any reference on the matter would be wonderful.

1

There are 1 best solutions below

0
On

I would advice you to follow the approach in https://medium.com/@willrigsbee/how-to-keep-track-of-clients-with-websockets-1a018c23bbfc It is better to create an object with key/value pair so that the key will be the userId and value will be the socket.