Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

713
Visualizações
ReferenceError: WebSocket is not defined in client side typescript react application

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda