security.nonce

  • Type:
type Nonce = string;
  • Default: undefined

Adding a nonce attribute to the scripts resources introduced for HTML. This allows the browser to determine whether the script can be executed when it parses inline scripts with matching nonce values.

Introduce nonce

The nonce mechanism plays a crucial role in Content Security Policy (CSP), enhancing webpage security. It allows developers to define a unique and random string value, i.e., nonce, for inline <script> tags and <style> tags within CSP.

When the browser parses inline scripts with matching nonce values, it allows them to be executed or applied, otherwise CSP will prevent them from running. This effectively prevents potential Cross-Site Scripting (XSS) attacks. It's worth noting that a new nonce value should be generated each time the page is accessed.

For more information about nonce, you can refer to:

Example

By default, nonce is not enabled by Rsbuild, you can define this value based on your needs:

export default {
  security: {
    nonce: 'CSP_NONCE_PLACEHOLDER',
  },
};

Typically, we can define a fixed value in the project, and replace it with a random value on downstream servers such as Nginx, Web Server, gateway, etc.

Scope of Effect

The security.nonce config adds the nonce attribute to the following tags:

  • All <script> tags generated by Rsbuild
  • All <style> tags generated by Rsbuild
  • Dynamic <script> tags generated by Rspack (implemented by the __webpack_nonce__ variable)

For <script> or <style> tags that already exist in the HTML template file, Rsbuild will not modify them. You can directly add the nonce attribute in the template.

For <script> or <style> tags inserted dynamically via JavaScript, you also need to set the nonce attribute yourself.