CSP vs Hugo Highlighting

QUICKTIPSRICSP

Last Modified: March 25, 2021

If you are using the code styling functionality of Hugo then you might have stumbled over a common issue when you are using Content Security Policies (CSP) and inline styles. Using CSPs is the proper way these days to secure your site code but it is considered (in the realm of CSPs) bad style to have your style sheets or JavaScript inlined into your page.

Proper CSP rules will not allow unsafe-inline in your CSP rules (because there is a reason, why it starts with unsafe). You could set this parameter to get rid of the error messages in your console, or you could ignore those errors. Or, configure your site setup to stop using inline styles for the highlight function, Markdown rendering and shortcodes.

First step: Configure Hugo to use classes for syntax highlighting in your configuration:

[markup]
[markup.highlight]
noClasses = false
style = "monokai"

Then on the command prompt create the style sheet for the highlight shortcode or Markdown code fences:

hugo gen chromastyles --style=monokai > syntax.css

Add this file in your theme or style sheet pipeline and the code will be highlighted as before, but uses style sheet classes instead of inline styles.

Now everyone is happy. You and your CSP.