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?

2
  • 1
    Are you using next.js or anyother React frameworks? Commented Jan 3, 2022 at 21:48
  • Yes. I'm using next.js. Commented Jan 3, 2022 at 21:54

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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 */}</>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.