EDDYMENS

Published a week ago

How To Identify Users In A WebSocket Connection|NodeJS

server.js

01: const WebSocket = require('ws'); 02: 03: const server = new WebSocket.Server({ port: 8080 }); 04: 05: server.on('connection', (socket) => { 06: 07: socket.on('message', (request) => { 08: const parsedRequest = JSON.parse(request); 09: if (parsedRequest.action == 'auth') { 10: const jwtToken = parsedRequest.payload; 11: const user = {id: 1, name: 'John Doe'}; // Authenticate user using JWT token (jwtToken) 12: socket.user = user; //append user object to socket 13: socket.send(JSON.stringify({ action: 'auth', payload: { registered: true } })); 14: return; 15: } 16: socket.send(`Your message: ${parsedRequest.payload}, User: ${JSON.stringify(socket.user)}`); 17: }); 18: socket.on('close', () => { 19: console.log('Client disconnected'); 20: }); 21: }); 22: 23: console.log('WebSocket server is running on ws://localhost:8080');

Attaching an Identity Object to a User's Open Socket

The WS package [β†—] creates an object for each active WebSocket connection. In the example code above, this object is represented by the socket variable.

Since this object represents each active connection, which essentially corresponds to a user, we can attach the user object to it as well.

After authenticating a user and retrieving their details from the database, you can attach the user object to the socket object, as demonstrated on line 12 [β†’].

Managing Server Restarts

It is important to note that the user object will be lost if the connection is closed or if the server is restarted.

You will need to handle reauthenticating users by starting the authentication process each time the client connects to the server.

Frontend code:

index.html

01: ... 02: socket.addEventListener('open', () => { 03: appendMessage('Connected to the server'); 04: socket.send(JSON.stringify({ action: "auth", payload: 'token' })); // send JWT to server to re-authenticate 05: }); 06: ...

Here is another article you might like 😊 How To Roll Back To A Previous Commit Without Losing Git History