# Source: https://rsbuild.dev/config/security/nonce.md

# security.nonce

* **Type:**

```ts
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:

* [nonce - MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce)
* [webpack - Content Security Policies](https://webpack.js.org/guides/csp/)

## Example

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

```ts title="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:

* All `<script>` tags generated by Rsbuild
* All `<style>` tags generated by Rsbuild
* All [`<link rel="preload" as="script">`](/config/performance/preload.md) tags generated by Rsbuild
* Dynamic `<script>` tags generated by Rspack (implemented by the [\_\_webpack\_nonce\_\_](https://rspack.rs/api/runtime-api/module-variables#__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.