socketio / socketio/socket.io

Uncaught TypeError: Illegal invocation

Open
#5,308 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

to triage
Dominant language
TypeScript
Stars
63.2k
Forks
10.3k
Avg merge
11d 20h
Merged PRs (30d)
2

Description

Describe the bug
It produces Uncaught TypeError: Illegal invocation error when calling io()

context: I'm working in a react project where valtio is used for state manamement.

To Reproduce

Socket.IO server version: 4.8.1

Server

Using Nest.js for server. The server is working fine.

Socket.IO client version: 4.8.1

Client

// (next.js projec) the valtio store
'use client';
import {proxy, ref} from "valtio";
import {devtools, useProxy} from "valtio/utils";
import {IS_PRODUCTION_MODE, isServer} from "@/util/constants";
import {io, Socket} from "socket.io-client";
import {endpoints} from "@/util/urls";

type MsgModule<Actions = any> = {
  socket: Socket;
  connecting: boolean;
  actions: Actions
}

type Data = {
  message: MsgModule;
}
export const socketStore = proxy<Data>({
  message: {
    socket: io(endpoints.api.baseUrl + '/message', {
      auth: {
        token: ''
      },
      autoConnect: false
    }),
    connecting: false,
    actions: ref({
      abc: () => {}
    }),
  },
});

// socketStore.message.

export const useStoreSockMsg = () => useProxy(socketStore.message);

devtools(socketStore, {
  name: 'socket',
  enabled: !isServer && !IS_PRODUCTION_MODE,
});

export const socketActions = {
  connectMessageSocket(accessToken: string) {
    if (socketStore.message.socket.connected || socketStore.message.connecting) return;

    console.log('proceed to socket connection with token', accessToken)

    socketStore.message.socket = io(
      endpoints.api.baseUrl + '/message',
      {
        auth: {
          token: accessToken,
        },
        autoConnect: false,
      }
    );

    // Listen for connection events
    socketStore.message.socket.on('connect', () => {
      console.log('socket is connected')
    });

    socketStore.message.socket.on('disconnect', () => {
      console.log('socket is disconnected')
    });

    // Handle auth errors (e.g., expired token)
    socketStore.message.socket.on('connect_error', async (err) => {
      console.log('socket connection err: ', err.message)

      // if (err.message === 'Unauthorized') {
      //   retry connection with updated token ...
      // }
    });


    socketStore.message.socket.connect();
  },

  // Disconnect and cleanup
  disconnectSocket: () => {
    if (socketStore.message.socket) {
      socketStore.message.socket.disconnect();
    }
  },

};
// the component
function MessageSocket() {
  const userStore = useStoreUser();
  const sockStore = useStoreSockMsg();

  useEffect(() => {
    if (sockStore.socket.connected || !userStore.at) return; // at is access token
    socketActions.connectMessageSocket(userStore.at); // calling this producting the err: Uncaught TypeError: Illegal invocation

    return () => socketActions.disconnectSocket();
  }, [userStore.at, sockStore.socket.connected]);

  useEffect(() => {
    console.log('sock connected?', sockStore.socket.connected)
  }, [sockStore.socket.connected]);

  // ...
}

Expected behavior
Obviously expectation was to successfully connect, The official docs has a guide on how to use with react but that doesn't covers how to use with authentication when the token becomes available later.

Platform:

  • Device: A Desktop PC
  • OS: Ubuntu 24.04

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the io() calls and connectMessageSocket entry point in the provided Next.js client reproduction, then isolate whether wrapping the Socket instance in the Valtio proxy causes the invocation error. Reproduce the authenticated connection flow with the token initially unavailable and verify that it connects successfully once the token is supplied.

Written by the indexing model from the issue text.

Assessment

Tech stack
nextjs, react, typescript
Domain
backend, frontend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.