> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# 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 [`import.meta.rspackNonce`](https://rspack.rs/api/runtime-api/module-variables#importmetarspacknonce) variable)
- Supported tags added through [`html.tags`](/config/html/tags.md), where `attrs.nonce` can override the default value or be set to `false` to omit the attribute

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.
