"ReferenceError: WebSocket is not defined" when using RxJs WebSocketSubject and Angular Universal
All it takes is this:
// set WebSocket on global object
(global as any).WebSocket = require('ws');
And of course, we need the ws
dependency as well in the package.json:
npm i ws -s
The RxJS webSocket function can receive a WebSocket Constructor as an argument. This can be used to run webSocket in a non-browser/universal environment like this.
const WebSocketConstructor = WebSocket || require('ws')
const socket: WebSocketSubject<any> = webSocket({
url: 'wss://echo.websocket.org',
WebSocketCtor: WebSocketConstructor,
});