webpackthymeleafcontent-security-policywebpack-5

How to add nonce attribute to script tags using webpack 5


I am using webpack 5 with HtmlWebpackPlugin to build my frontend SPA.

I need to add nonce attribute to <script ... tags injected by HtmlWebpackPlugin.

How do I do it?

Extra question: after that I am using this pages as Thymeleaf templates before serving. How do I inject nonce value?


Solution

  • If you were using webpack 4, there is plenty of fish in the sea — just use any plugin which injects attributes, such as script-ext-html-webpack-plugin or html-webpack-inject-attributes-plugin

    However, most of the plugins mentioned above do not work with webpack 5. The workaround is to use the HtmlWebpackPlugin templates.

    1. Set inject to false in HtmlWebpackPlugin options specified in webpack.config.
    2. In template add the following code which will insert all the generated scripts into resulting file:
        <% for (key in htmlWebpackPlugin.files.js) { %>
          <script type="text/javascript" defer="defer" src="<%= htmlWebpackPlugin.files.js[key] %>"></script>
        <% } %>
    
    1. Add all the necessary attributes in script. Thymeleaf example:
        <% for (key in htmlWebpackPlugin.files.js) { %>
          <script type="text/javascript" defer="defer" th:attr="nonce=${cspNonce}" src="<%= htmlWebpackPlugin.files.js[key] %>"></script>
        <% } %>
    

    Answer based on github post