socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

onAny bypass AsyncLocalStorage middleware

Open PolyFlyx-EFerry opened this issue 3 months ago • 1 comments

Describe the bug Upon using socket.IO alongside express, I wanted to create an AsyncLocalStorage with a middleware in my socket.IO connection. socket.useis a great tool, and work wonder when I was dealing with socket.on(...) shenanigans but now I need to use socket.onAny(...), and I can't seem to bind my storage to the callback of onAny. Is this the expected behavior ? Of yes, I believe this should be documented somewhere. Thanks a lot, and huge thanks for this great tool 🙏 !

To Reproduce

Please fill the following code example:

Socket.IO server version: 4.8.1

Server

import { Server } from "socket.io";
import { AsyncLocalStorage } from "async_hooks"

const asyncLocalStorage = new AsyncLocalStorage();

const io = new Server(3000, {});

io.on("connection", (socket) => {
  console.log(`connect ${socket.id}`);
  asyncLocalStorage.run({}, () => {
    socket.onAny((eventName, data) => {
      asyncLocalStorage.getStore() // This is undefined
    })
    socket.on("event", (data) => {
      asyncLocalStorage.getStore() // This is my store
    })
    next();
  })
  socket.on("disconnect", () => {
    console.log(`disconnect ${socket.id}`);
  });
});

Current workaround :

io.on("connection", (socket) => {
  socket.onAny((eventName, data) => {
    asyncLocalStorage.run({}, () => {
      asyncLocalStorage.getStore() // This works fine
    })
  })
  socket.on("disconnect", () => {
    console.log(`disconnect ${socket.id}`);
  });
});

Client has been tested with APIDog, but I don't believe this has anything to do with the client.

Expected behavior I was expecting to have access to my asyncLocalStorage, and the data inside of it, working the same way as on method does

Platform:

  • Device: Dell XPS
  • OS: Ubuntu 24.04

PolyFlyx-EFerry avatar Sep 01 '25 15:09 PolyFlyx-EFerry