close

security.nonce

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

Adds a nonce attribute to script resources injected into HTML. This lets the browser decide whether inline scripts with matching nonce values can be executed.

What is nonce

The nonce mechanism is a key part of Content Security Policy (CSP) and enhances webpage security. It lets developers define a unique, random string (the nonce) for inline <script> and <style> tags within CSP.

When the browser parses inline scripts with a matching nonce, it allows them to run; otherwise, CSP blocks them. 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

Rsbuild does not enable nonce by default. You can define this value based on your needs:

rsbuild.config.ts
export default {
  security: {
    nonce: 'CSP_NONCE_PLACEHOLDER',
  },
};

Typically, you can define a placeholder value in the project, then have downstream servers such as Nginx, web servers, or gateways replace it with a random string.

Scope of effect

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

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.