How to implement async event tracking in JS runtime without blocking RPC response?

I’m currently using the JavaScript runtime in Nakama , and I want to implement event tracking (e.g., sending to Mixpanel) when a custom RPC is called. However, I want to return the RPC response immediately to the client and send the tracking event asynchronously in the background , without blocking the response.

I understand that the JS runtime does not allow us to register custom event handlers for nk.event(…). So I was thinking of the following workaround — could you please confirm if this approach is correct or suggest a better one?

Proposed Flow:

  1. In the JS custom RPC, I call:
nk.event({
  name: "analytic_event",
  properties: { action: "purchase", userId: ctx.userId },
  userId: ctx.userId,
  timestamp: Date.now(),
});
  1. This RPC returns immediately to the client.
  2. On the Go runtime side, I register a handler for this custom event (analytic_event), and inside it, I call external services like Mixpanel to track the event.

Questions:

  • Is this pattern valid?
  • Can Go runtime subscribe to events created by JS runtime using nk.event()?
  • Is there a more elegant way to achieve async side effects after an RPC call in JS? (return rpc response to client fast and do some action after return to client)

Thanks

base on this discussion:

ChatGPT give some suggestions something like

setTimeout(() => {
  nk.rpc("track_analytic_event", JSON.stringify({
    action: "purchase",
    userId: ctx.userId
  }));
}, 0);

Does this code work?

Yes, this pattern is valid.

The Go runtime can subscribe to events created by the JS runtime using nk.event. That’s currently the only way to do it as far as I know. We do exactly this for sending events to Mixpanel asynchronously.