2

I am working on a React frontend application and I am trying to set up a WebSocket connection to my Golang backend server.

So far I have a simple class that is supposed to initiate a websocket connection using the native websocket object. It is failing with error ReferenceError: WebSocket is not defined

export class MyService implements RealtimeService {
  socket: WebSocket;
  constructor() {
    console.log('initializing websocket connection');
    this.socket = new WebSocket('ws://localhost:50000');


    this.socket.on("open", (event) => {
      console.log('connection established');
    });

    this.socket.on("error", (event) => {
      console.log('connection failed', event)
    });

    this.socket.on('message', (event) => {
      console.log('received message from server ', event.data);
    })

    this.socket.on('close', (event) => {
      console.log('connection closed ', event);
    })
  }

  serviceName(): string {
    //TODO: implement
    return "";
  }

  subscribe(channelName: string): any {
    //TODO: implement
    return new Channel();
  }
}

I have tried installing the ws package using npm install ws and import WebSocket from 'ws'; based on the solution from here https://stackoverflow.com/a/52037864/3083825 but it looks like the ws package does not work on the browser anymore. It fails with error Error: ws does not work in the browser. Browser clients must use the native WebSocket object

My question is, why isn't the native WebSocket object working? When I create a simple javascript file, the native WebSocket object works fine but it doesn't work in this react app. How can I make it work?

SomeGuyFortune
  • 1,024
  • 13
  • 26

2 Answers2

0

Instead of defining Websocket in constructor try to use componentDidMount as such :

   componentDidMount() {
         let ws = new WebSocket('ws://localhost:50000');
    }

DOM must be completely loaded in order for the browser to access Websocket. I think this is the reason you are getting that error.

again I advise you to ditch classbased components and rewrite your code with functional components using the hook useEffect.

Hypothesis
  • 1,208
  • 3
  • 17
  • 43
0

In next js , you need to call WebSocket function inside useEffect , cause WebSocket is a browser function and will only be available after component has mounted in next , so what you can do is implement like below

function MyService(){
    useEffect(()=>{
        let ws = new WebSocket('ws://localhost:50000');
    },[])
  return <>{/* Your JSX */}</>
}
Goutham J.M
  • 1,726
  • 12
  • 25