registerRtBefore for channel message not working

Hi Pro,

I was trying to modify the ChannelMessageSend feature with before hook but getting JS runtime error during testing with the sample code I found on [docs] (Nakama: Real-time Chat | Heroic Labs Documentation)

server:
nakama:3.2.1 in docker

and this is my sample code

let InitModule: nkruntime.InitModule = (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, initializer: nkruntime.Initializer) => {
  logger.info("Hello world!");

  let rtBeforeChannelMessageSend: nkruntime.RtBeforeHookFunction<nkruntime.Envelope> = function (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, envelope: nkruntime.Envelope): nkruntime.Envelope {
    let e = envelope as nkruntime.EnvelopeChannelMessageSend;
    if (e == null) {
      return e;
    }

    if (e.channelMessageSend.content.indexOf('Bad Word') !== -1) {
      throw new Error("Profanity detected");
    } else {
      logger.info("test")
      logger.info("test")
      logger.info("test")
      logger.info("test")
      logger.info("test")
    }

    return e;
  }

  initializer.registerRtBefore("ChannelMessageSend", rtBeforeChannelMessageSend);
}


error getting from server:

{"level":"error","ts":"2022-05-19T03:09:04.990Z","caller":"server/runtime_javascript.go:205","msg":"JavaScript runtime function invalid.","uid":"188d0185-b8f1-4df6-81c8-8af1d11c6321","sid":"0a5b414e-d721-11ec-9467-7106fdcb5b46","cid":"2","key":"rtBeforeChannelMessageSend"}

Hi @kennot welcome to the forum.

The issue you’re experiencing is due to a limitation of the embedded JavaScript VM.
To resolve this issue please define your rtBeforeChannelMessageSend function outside of the InitModule function.

e.g.

let rtBeforeChannelMessageSend: nkruntime.RtBeforeHookFunction<nkruntime.Envelope> = function (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, envelope: nkruntime.Envelope): nkruntime.Envelope {
  // ...
}

let InitModule: nkruntime.InitModule = function (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, initializer: nkruntime.Initializer) {
  // ...
  initializer.registerRtBefore("ChannelMessageSend", rtBeforeChannelMessageSend);
}

I hope this helps.

Kind regards,
Tom