stompjs icon indicating copy to clipboard operation
stompjs copied to clipboard

TypeError: WebSocket is not a constructor

Open RichardBrowning opened this issue 1 year ago • 1 comments

Error Description

I am running a React JS application to connect to a local Spring Boot service. When running .activate(), this error shows up:

Uncaught runtime errors:
ERROR
WebSocket is not a constructor
TypeError: WebSocket is not a constructor
    at Client._createWebSocket (http://localhost:3000/static/js/bundle.js:185684:19)
    at Client._connect (http://localhost:3000/static/js/bundle.js:185618:28)

Code

I implemented a web socket handler class

import { Client } from '@stomp/stompjs';
import { WebSocket } from 'ws';

Object.assign(global, { WebSocket });
...
class WebSocketHelper {
	constructor(serverUrl = 'ws://localhost:8080/websocket') {
		this.serverUrl = serverUrl;
		this.cryptoHelper = new CryptoHelper(seed);
		this.users = {};
		this.groups = {};
		
		this.stompClient = new Client({
			brokerURL: serverUrl,
			onConnect: (frame) => {
				console.log("connected to the server");
				this.stompClient.subscribe("/user/queue/listen", (packet) =>{
					packet = Array.from(packet._binaryBody);
					this.parse_packet(this.cryptoHelper.decrypt_packet(packet));
				});
			},
			onWebSocketError: (error) => {
				console.error("Websocket error: ", error);
			},
			onStompError: (frame) => {
				console.error("Stomp error: ", frame.headers.message);
			},
		});

		console.log("Connecting to the server");
		this.stompClient.activate();
	}
...

The error is triggered when calling the .activate() method

Dependency Versions

  "dependencies": {
    "@stomp/stompjs": "^7.0.0",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.3.3",
    "emoji-picker-react": "^4.9.2",
    "localforage": "^1.10.0",
    "match-sorter": "^6.3.4",
    "react": "^18.2.0",
    "react-bootstrap": "^2.10.2",
    "react-dom": "^18.2.0",
    "react-ionicons": "^4.2.1",
    "react-responsive": "^10.0.0",
    "react-router-dom": "^6.22.3",
    "react-scripts": "5.0.1",
    "sockjs-client": "^1.6.1",
    "sort-by": "^1.2.0",
    "stomp-websocket": "^2.3.4-next",
    "web-vitals": "^2.1.4",
    "ws": "^8.16.0"
  },

RichardBrowning avatar Apr 25 '24 01:04 RichardBrowning

Where are trying to run this, on a browser or with NodeJS?

In either case please follow the tutorial at https://stomp-js.github.io/guide/stompjs/using-stompjs-v5.html

kum-deepak avatar Apr 26 '24 09:04 kum-deepak