const ws = initChatService(); function initChatService() { const ws = new WebSocket("ws://localhost:3000/chat-socket"); ws.onmessage = function (event) { console.log(event); }; ws.onopen = function (event) { console.log("Opening the socket"); ws.send(JSON.stringify({ hello: "world" })); }; ws.onclose = function (event) { console.log("Closing the socket"); }; ws.onerror = function (event) { console.log(event); }; return ws; }