- Published on
Simple Way to Keep WS Client State in NodeJS
- Authors
- Name
- Yair Mark
- @yairmark
I [previously](/03-05-2019-setting-up-a-basic-websocket-client-server-nodejs/] spoke about how to setup a basic websocket server in NodeJS. One thing that I was not sure about at the time was how to keep track of ws client state on the server side.
It turns out this is fairly simple although not 100% sure how production grade this is:
import uuidv4 from 'uuid/v4';
...
// wss => web socket server
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
//this gets hit when the ws connection is first established
ws.on('message', (message)=> {
ws.id = uuidv4();
//this is hit when the ws receives a message
// handle message here
const detail = JSON.parse(message);
if(detail && detail.type === 'topic-you-expose') {
ws.clients.forEach((client) => {
if(client != ws && client.readyState === WebSocket.OPEN){
client.send(detail.payload);
}
});
}
})
});
In the above after the ws.on('message'
I assign the websocket client (which has been given the name ws
in this case) an id using the uuid library. You can assign any value you want in the above I just called it id
by attaching it to the ws
object using ws.id = uuidv4();
. You can then easily access these fields by simply going ws.id
or ws.yourField
.