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

AI-generated summary

The author, jamesmarkcook, shares their solution for using MessageBus with a custom Discourse frontend app on a different origin. Initially, they encountered a CORS issue due to the frontend being served from a different origin than Discourse.

They discovered that Discourse sets the Access-Control-Allow-Origin header to Discourse.base_url_no_prefix for the MessageBus environment, assuming it will be used with the default Ember frontend.

To customize this, jamesmarkcook used the MessageBus.extra_response_headers_lookup method to add extra headers to the MessageBus environment without overriding important Discourse logic. They provided an example of the code used in their plugin, which sets the Access-Control-Allow-Origin header to a custom domain.

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|
    env["__mb"][:extra_headers].merge({
      "Access-Control-Allow-Origin" => "http://your-custom-domain.com"
    })
  end

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!

10 Likes