JavaScript - ReferenceError: WebSocket is not defined

The code you're referencing in your question is client-side code. WebSocket is available directly in browsers.

For your Node.js server-side code, look at the ws NPM package.

So, how to implement WebSockets (client side) on NodeJS?

You don't. Node.js is server-side, not client-side.


I'm leaving this here for people having trouble with the @stomp/stompjs package in a node app.

Add this line:

Object.assign(global, { WebSocket: require('ws') });

also, don't forget to npm install ws


Try

const WebSocket = require('ws');
var socket = new WebSocket('ws://localhost:3000');

Then

npm i ws

and retry. It's work with my case


When you are trying to run JavaScript, usually, you run it either in Browser or in NodeJS.

Browser and NodeJS are different JavaScript runtime.

WebSocket itself is a application layer protocol, you need to use API to employ it.

Currently(05-Dec-2019),

most browsers support WebSocket API for developer to use WebSocket.

NodeJS does not provide any OOTB API for developer to use WebSocket, you need 3rd lib to use WebSocket (e.g. https://github.com/websockets/ws).

The example you followed is using WebSocket API in browser.

Hope it helps.