ReferenceError: WebSocket is not defined when using Angular Universal for SSR

Bug Report

Current Behavior
I use WebSocketSubject and webSocket in my angular universal 6.x project, which works fine on the browser platform. However, when running the node web server (that contains the SSR stuff (Server-Side Rendering)), an error is thrown:

ReferenceError: WebSocket is not defined

Reproduction

Example code:

import { WebSocketSubject, webSocket } from 'rxjs/webSocket';

const socket: WebSocketSubject<any> = webSocket('wss://echo.websocket.org');
socket.subscribe(msg => doSomething(msg));

Expected behavior
No error

Environment

  • Runtime: Angular 6
  • RxJS version: 6.2.0, 6.2.1, 6.2.2 (tested all)
  • Loader, build configuration:
# install dependencies
npm install

# build angular bundles for browser and server platforms
npm run build:client-and-server-bundles

# build the webserver
npm run webpack:server

# start the webserver
npm run serve:ssr

# the app is now being served at http://localhost:8081/
# open it in the browser and the error will occur: 'ReferenceError: WebSocket is not defined'

Additional info

  • I’m aware of #3692, which is why I tried more recent versions but it didn’t fix the issue.
  • I also opened a referring issue on the angular universal repo.

1 possible answer(s) on “ReferenceError: WebSocket is not defined when using Angular Universal for SSR

  1. Since webSocketSubject is a wrapper around websocket object from browsers, it makes perfectly sense not to be available in the server. No one browser APIs are available when using Angular/rxjs in the server.