Skip to content

Best practice for cross-namespace event emission from handlers? #596

@simwai

Description

@simwai

Use Case

I have a scenario where a handler in one namespace (/chat) needs to emit an event to a different namespace (/subscription). Specifically:

  • User sends a message via /chat namespace
  • If they hit their daily limit, I need to emit messageLimitReached to the /subscription namespace (where subscription-related events are handled)

Current Solution

I'm currently passing the io instance as a closure variable to the action factory:

export function createChatSocketActions(
  chatService: ChatService,
  io: Server // <-- Pass io manually
) {
  const sendMessage = chatFactory.build({
    async handler({ client, withRooms }) {
      // ...
      if (userHitLimit) {
        // Cross-namespace emit
        io.of("/subscription")
          .to(`user:${userId}`)
          .emit("messageLimitReached", {});
      }
    },
  });
}

This works, but feels like it might not be the intended pattern.

Question

What's the recommended approach for cross-namespace communication in zod-sockets?

Options I can think of beside my current approach:

  1. Add io to handler context - simple but maybe too permissive?
  2. Add a helper like emitToNamespace(ns, room, event, data) in the handler context
  3. Extend withRooms() to support .toNamespace(ns) or similar

Would love guidance on the "blessed" way to handle this, or if it's worth considering adding official support for cross-namespace operations in the library.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions