Using MessageBus with a custom Discourse frontend app on a different origin

I wanted to just document this here in case anyone else is trying to do the same and needs a little guidance.

I’m currently working on a React frontend paired with a Discourse backend and a plugin customising some Discourse functionality. I wanted to get MessageBus working with the custom frontend app but I hit a CORS issue as the frontend is being served from a different origin to Discourse.

I noticed that Discourse was setting the Access-Control-Allow-Origin header to Discourse.base_url_no_prefix for the MessageBus environment as it’s naturally assumed MessageBus will be working with the Discourse default Ember frontend.

As documented over at the MessageBus github readme it’s possible to add in extra headers to the MessageBus environment which is exactly what the Discourse MessageBus initializer is doing and where Access-Control-Allow-Origin is being set to Discourse.base_url_no_prefix.

In order to customise that I added the following code to my plugin:

  MessageBus.extra_response_headers_lookup do |env|
      "Access-Control-Allow-Origin" => ""

This has the benefit of not overriding important Discourse logic when determining the MessageBus environment which is established from calling setup_message_bus_env in the Discourse initializer, whilst still allowing custom values.

I realise this setup may be quite obvious for many of the developers on here but I thought it was worth documenting as it isn’t always easy to put the pieces together and if it saves one person an hour trying to figure this out then great!

Obviously if anything above is incorrect or inaccurate then please let me know and I will edit!