4

Since I want to enable Content Security Policy (CSP) with nonce attribute in style, so I need to set nonce in style dynamically by the code.

The webpack setting:

devServer: {
  contentBase: "./dist",
  watchContentBase: true,
  headers: {
    "Content-Security-Policy": "style-src 'nonce-test1'"
  }
}

However, the nonce attribute is generated by server, and will not be the same all the time, so I can not hard coded nonce: test1 in style-loader.

I have found lazy loading style, but I have not found articles or tutorials related to set nonce attribute dynamically when <style> is loaded by code.

How to add nonce to <style> by code?

index.ts

import styles from './styles.lazy.css';

export class MyMainClass {
  constructor(nonce) {
    loadStyle(nonce);
  }

  private loadStyle(nonce) {

    // I need to set nonce before styles are loaded, otherwise csp error will occur.
    styles.setNonceAttribute(nonce)???

    styles.use();
  }
}

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.lazy\.css$/i,
        use: [
          {
            loader: 'style-loader', 
            options: {
              injectType: 'lazyStyleTag', 
              attributes: {
                nonce: "initialNonce"
              }
            } 
          },
          'css-loader',
        ],
      },
    ],
  },
};
obelisk0114
  • 201
  • 3
  • 13

1 Answers1

-2

On the next page of webpack - There are two ways to work with nonce:

  • using the attributes option
  • using the webpack_nonce variable and examples of code.

Or it doesn't work in your case?

granty
  • 7,234
  • 1
  • 14
  • 21
  • If I created `create-nonce.js` with `__webpack_nonce__ = 'initialNonce';`, I don't know how to change `webpack_nonce` in the `index.js`. It always shows `can not create property...` – obelisk0114 Oct 01 '20 at 07:17
  • hard-coded nonce(and comments below): https://github.com/cssinjs/jss/issues/559#issuecomment-359274297; How to set Webpack interpolate the nonce expression at runtime instead of build time; https://stackoverflow.com/questions/49639625/how-do-i-integrate-the-value-of-webpack-nonce-with-my-content-security-poli – granty Oct 01 '20 at 17:03
  • The methods in two links used back-end to generate `index.html` and insert `nonce` in it. My current work is to build a script (e.g. `MyJS.js`) to create some components that can be used in the website. So the ` – obelisk0114 Oct 02 '20 at 04:37