This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: csp-level-3-dynamic-nonce-streaming-ssr-invariant

CSP Level 3 Dynamic Nonce Propagation in Chunked Streaming SSR

Enforces cryptographic nonce generation per HTTP request and continuous injection into both HTTP response headers and chunked HTML streaming boundaries. Prevents Cross-Site Scripting (XSS) bypasses and React/Next.js hydration mismatches caused by static nonce reuse or out-of-order asynchronous chunk rendering without proper nonce binding.

Prohibited Anti-Pattern: Reusing Static Nonces Across Requests or Emitting Inline Scripts Without Contextual Nonce Binding in Streaming Chunks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: CSP Level 3 Dynamic Nonce Propagation in Chunked Streaming SSR - Enforces cryptographic nonce generation per HTTP request and continuous injection into both HTTP response headers and chunked HTML streaming boundaries. Prevents Cross-Site Scripting (XSS) bypasses and React/Next.js hydration mismatches caused by static nonce reuse or out-of-order asynchronous chunk rendering without proper nonce binding.
globs: src/**/*.{ts,tsx}, app/**/*.{ts,tsx}, middleware.{ts,js}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/csp-level-3-dynamic-nonce-streaming-ssr-invariant"
---

# CSP Level 3 Dynamic Nonce Propagation in Chunked Streaming SSR

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Reusing Static Nonces Across Requests or Emitting Inline Scripts Without Contextual Nonce Binding in Streaming Chunks

## System Constraints
You are a Principal Security Architect enforcing CSP Level 3 Dynamic Nonce Streaming SSR Invariants. Mandate that every HTTP request dynamically generates a cryptographically secure, base64-encoded 128-bit (16-byte) or 256-bit (32-byte) pseudo-random nonce. This nonce must be bound directly to the Content-Security-Policy response header via standard directives (`'nonce-${nonce}' 'strict-dynamic'`) and propagated synchronously through request storage (e.g., AsyncLocalStorage, React Server Context, or framework headers) into every rendered HTML chunk. Never allow static nonces, client-side nonce exposure in hydration payloads, or inline `<script>` tags lacking the matching dynamic nonce attribute.

## Strict Guidelines
- Engineers MUST ALWAYS generate a fresh, cryptographically strong random nonce (using `crypto.randomBytes` or `crypto.getRandomValues`) per incoming HTTP request within edge/server middleware.
- Engineers MUST NOT rely on build-time, global, or cached nonces across multiple distinct HTTP requests.
- Services MUST emit the Content-Security-Policy header containing `'nonce-${nonce}'` alongside `'strict-dynamic'` to adhere to CSP Level 3 cascading execution rules.
- Components rendering inline scripts or preloaded script links inside streaming SSR boundaries MUST consume the active request-bound nonce via React Server Context or `AsyncLocalStorage`.
- Components NEVER include the CSP nonce attribute inside dehydrated client JSON state (e.g., `window.__INITIAL_STATE__`) to prevent client-side DOM reflection attacks.

## Bad vs Good Implementations
### Dynamic CSP Nonce Propagation in Next.js / Node.js Streaming SSR

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reusing a static nonce across requests completely invalidates CSP Level 3 security by allowing attackers to predict the nonce for reflected or stored XSS. Furthermore, emitting inline scripts during streaming SSR without passing the request-scoped dynamic nonce causes modern browsers to drop the script and triggers hydration mismatches.
```typescript
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// ANTI-PATTERN: Static nonce reused across all requests, vulnerable to replay and injection
const STATIC_NONCE = 'c3RhdGljLW5vbmNlLWZvci1jYWNoZQ==';

export function middleware(request: NextRequest) {
  const response = NextResponse.next();
  // Flaw 1: Static nonce defeats CSP Level 3 protection
  response.headers.set(
    'Content-Security-Policy',
    `default-src 'self'; script-src 'nonce-${STATIC_NONCE}' 'strict-dynamic';`
  );
  return response;
}

// Component rendering without propagating dynamic request context
export function ServerInjectedAnalytics() {
  return (
    // Flaw 2: Omitting dynamic nonce causes browser CSP violation or hydration failure in streaming chunks
    <script
      dangerouslySetInnerHTML={{
        __html: `window.dataLayer = window.dataLayer || [];`,
      }}
    />
  );
}
```

#### Production Standard (Correct)
> **Standard**: A distinct, cryptographically secure nonce is generated on every request in middleware and forwarded into request headers. Streaming React Server Components resolve the per-request nonce synchronously via the headers context, binding the exact matching nonce to inline scripts inside streamed HTML chunks without exposing it to client-state serialization.
```typescript
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { headers } from 'next/headers';

export function middleware(request: NextRequest) {
  // 1. Generate cryptographically strong, 128-bit base64-encoded nonce per request
  const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
  const cspHeader = `default-src 'self'; script-src 'nonce-${nonce}' 'strict-dynamic' https: 'unsafe-inline'; object-src 'none'; base-uri 'none';`;

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-nonce', nonce);
  requestHeaders.set('Content-Security-Policy', cspHeader);

  const response = NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });
  response.headers.set('Content-Security-Policy', cspHeader);
  return response;
}

// Streaming-safe React Server Component
export async function ServerInjectedAnalytics() {
  // 2. Consume per-request nonce from server context within chunk boundary
  const headerList = await headers();
  const nonce = headerList.get('x-nonce') ?? undefined;

  return (
    <script
      nonce={nonce}
      dangerouslySetInnerHTML={{
        __html: `window.dataLayer = window.dataLayer || [];`,
      }}
    />
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: CSP Level 3 Dynamic Nonce Propagation in Chunked Streaming SSR

CSP Level 3 Dynamic Nonce Propagation in Chunked Streaming SSR defines an industrial-grade behavioral standard for security engineering. Enforces cryptographic nonce generation per HTTP request and continuous injection into both HTTP response headers and chunked HTML streaming boundaries. Prevents Cross-Site Scripting (XSS) bypasses and React/Next.js hydration mismatches caused by static nonce reuse or out-of-order asynchronous chunk rendering without proper nonce binding. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Reusing Static Nonces Across Requests or Emitting Inline Scripts Without Contextual Nonce Binding in Streaming Chunks Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftReusing Static Nonces Across Requests or Emitting Inline Scripts Without Contextual Nonce Binding in Streaming ChunksCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS generate a fresh, cryptographically strong random nonce (using `crypto.randomBytes` or `crypto.getRandomValues`) per incoming HTTP request within edge/server middleware.

Engineers MUST ALWAYS generate a fresh, cryptographically strong random nonce (using `crypto.randomBytes` or `crypto.getRandomValues`) per incoming HTTP request within edge/server middleware.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT rely on build-time, global, or cached nonces across multiple distinct HTTP requests.

Engineers MUST NOT rely on build-time, global, or cached nonces across multiple distinct HTTP requests.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST emit the Content-Security-Policy header containing `'nonce-${nonce}'` alongside `'strict-dynamic'` to adhere to CSP Level 3 cascading execution rules.

Services MUST emit the Content-Security-Policy header containing `'nonce-${nonce}'` alongside `'strict-dynamic'` to adhere to CSP Level 3 cascading execution rules.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Components rendering inline scripts or preloaded script links inside streaming SSR boundaries MUST consume the active request-bound nonce via React Server Context or `AsyncLocalStorage`.

Components rendering inline scripts or preloaded script links inside streaming SSR boundaries MUST consume the active request-bound nonce via React Server Context or `AsyncLocalStorage`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER include the CSP nonce attribute inside dehydrated client JSON state (e.g., `window.__INITIAL_STATE__`) to prevent client-side DOM reflection attacks.

Components NEVER include the CSP nonce attribute inside dehydrated client JSON state (e.g., `window.__INITIAL_STATE__`) to prevent client-side DOM reflection attacks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is CSP Level 3 Dynamic Nonce Propagation in Chunked Streaming SSR critical for AI coding assistants?

Enforces cryptographic nonce generation per HTTP request and continuous injection into both HTTP response headers and chunked HTML streaming boundaries. Prevents Cross-Site Scripting (XSS) bypasses and React/Next.js hydration mismatches caused by static nonce reuse or out-of-order asynchronous chunk rendering without proper nonce binding. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Reusing Static Nonces Across Requests or Emitting Inline Scripts Without Contextual Nonce Binding in Streaming Chunks) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

CSP