A user reports a CORS error with relative paths in the highlight_js.rb file on Discourse sites, where code highlighting fails on efg.com but works on www.abc.com. The issue arises because relative paths like /highlight-js/efg.com/... result in a base URL of about:blank, causing CORS failures. Using an absolute URL resolves the problem Yt.w. Another user, simonk, explains that Discourse only adds Access-Control-Allow-Origin headers for CDN requests, which require the cdn_origin_hostname setting to be configured. After setting this to the normal domain name and clearing the CDN cache, highlighting works again simonk. The issue is linked to CDN configurations and the need for proper CORS headers.
The following code in lib/highlight_js.rb works on some domains but not others:
def self.path
"/highlight-js/#{Discourse.current_hostname}/#{version SiteSetting.highlighted_languages}.js"
end
I have two Discourse sites. This code works on the domain www.abc.com, but it doesn’t work on efg.com. In the browser console, I see the following error:
formatter.js:383 Uncaught (in promise) TypeError: Failed to resolve module specifier '/highlight-js/efg.com/9797975efac87d28baa695ae13ca72ccaf5120f5.js'. The base URL is about:blank because import() is called from a CORS-cross-origin script.
After modifying self.path in highlight_js.rb as follows:
def self.path
"https://#{Discourse.current_hostname}/highlight-js/#{Discourse.current_hostname}/#{version SiteSetting.highlighted_languages}.js"
end
the issue was resolved.
It appears that using a relative path like import('/highlight-js/efg.com/9797975efac87d28baa695ae13ca72ccaf5120f5.js')
causes a CORS issue, while using an absolute URL, import('https://efg.com/highlight-js/efg.com/9797975efac87d28baa695ae13ca72ccaf5120f5.js') , works fine.
Are you using a CDN on either of these sites? I have noticed that code highlighting is no longer working on my site, and I think it’s because of this:
In my case, my CDN is not returning an Access-Control-Allow-Origin header for the highlightjs file. I notice that Meta’s CDN does include that header, so I wonder what is different.
As a follow up, I set cdn_origin_hostname to the normal domain name of my Discourse instance, flushed the CDN cache, and now highlightjs is working again. I haven’t noticed any side effects…