Skip to content

onAny bypass AsyncLocalStorage middleware #5386

@PolyFlyx-EFerry

Description

@PolyFlyx-EFerry

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions