This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: react-19-server-actions-cryptographic-nonce-replay-prevention

React 19 Server Actions Cryptographic Nonce & Mutation Idempotency Boundary

Mandates cryptographically verifiable, single-use idempotency nonces across all stateful React 19 Server Actions. Defeats replay attacks, eliminates duplicate mutations during optimistic streaming retries, and prevents cross-site state injection in multi-step transitions.

Prohibited Anti-Pattern: Unbounded Server Action Invocations Permitting Replay Exploits and Concurrent Double-Mutation Execution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React 19 Server Actions Cryptographic Nonce & Mutation Idempotency Boundary - Mandates cryptographically verifiable, single-use idempotency nonces across all stateful React 19 Server Actions. Defeats replay attacks, eliminates duplicate mutations during optimistic streaming retries, and prevents cross-site state injection in multi-step transitions.
globs: src/**/*.{ts,tsx}, app/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-19-server-actions-cryptographic-nonce-replay-prevention"
---

# React 19 Server Actions Cryptographic Nonce & Mutation Idempotency Boundary

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unbounded Server Action Invocations Permitting Replay Exploits and Concurrent Double-Mutation Execution

## System Constraints
You are a Principal Security and Distributed Systems Architect enforcing atomic mutation boundaries in React 19. You must enforce strict single-use cryptographic nonce validation and atomic idempotency stores on all Server Actions that execute financial, stateful, or transactional mutations.

## Strict Guidelines
- Engineers MUST generate an ephemeral, cryptographically secure idempotency nonce on the client or session boundary prior to dispatching stateful Server Actions.
- Engineers MUST NOT rely on client-side button disabling or local state flags to prevent duplicate Server Action dispatches or network replay attacks.
- Server Actions MUST atomically verify, claim, and lock the mutation nonce via an ACID transaction or atomic distributed cache operation (e.g., Redis SETNX with TTL) before applying domain side-effects.
- Optimistic UI updates orchestrated via `useOptimistic` or `useActionState` MUST bind transition states to the deterministic nonce to guarantee predictable rollbacks upon concurrent conflicts or replay rejections.
- Server Actions MUST cryptographically bind the action payload and user session identifier to the nonce digest to defeat cross-session state injection and transaction parameter tampering.

## Bad vs Good Implementations
### React 19 Server Action with Nonce Validation & Atomic Consumption

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The action performs destructive database mutations without verifying request provenance, idempotency tokens, or cryptographic replay nonces. Client retries, optimistic transitions, or replay attacks will execute redundant transfers.
```typescript
// BAD: Vulnerable to replays, race conditions, and double-execution via network retry or fast-clicks
'use server';

import { db } from '@/lib/db';
import { revalidatePath } from 'next/cache';

export async function transferFundsAction(formData: FormData) {
  const recipientId = formData.get('recipientId') as string;
  const amount = Number(formData.get('amount'));

  // CRITICAL: No replay protection or idempotency guarantee.
  // If the user double-clicks or the client retries an optimistic stream, balance is deducted twice.
  await db.account.decrement({ where: { userId: 'current-user' }, data: { balance: amount } });
  await db.account.increment({ where: { userId: recipientId }, data: { balance: amount } });

  revalidatePath('/dashboard');
  return { success: true };
}
```

#### Production Standard (Correct)
> **Standard**: The server action verifies an HMAC-signed payload tying the nonce to the authenticated session and inputs. It uses an atomic distributed lock (Redis NX) and transaction-bound mutation ledger to guarantee strict single-execution semantics under all network conditions.
```typescript
// GOOD: Enforces atomic cryptographic nonce reservation, session binding, and deterministic rollback
'use server';

import { db } from '@/lib/db';
import { redis } from '@/lib/redis';
import { verifySession } from '@/lib/auth';
import { createHmac, timingSafeEqual } from 'node:crypto';

interface TransferResult {
  success: boolean;
  error?: string;
}

function verifyNonceSignature(nonce: string, signature: string, userId: string, amount: number): boolean {
  const secret = process.env.IDEMPOTENCY_SECRET!;
  const expectedSignature = createHmac('sha256', secret)
    .update(`${nonce}:${userId}:${amount}`)
    .digest('hex');
  
  return timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expectedSignature, 'hex'));
}

export async function transferFundsAction(
  _prevState: TransferResult | null,
  formData: FormData
): Promise<TransferResult> {
  const session = await verifySession();
  const recipientId = formData.get('recipientId') as string;
  const amount = Number(formData.get('amount'));
  const nonce = formData.get('mutationNonce') as string;
  const signature = formData.get('signature') as string;

  if (!nonce || !signature || isNaN(amount) || amount <= 0) {
    return { success: false, error: 'INVALID_MUTATION_PAYLOAD' };
  }

  // Cryptographically verify parameter binding to defeat cross-site state injection
  if (!verifyNonceSignature(nonce, signature, session.userId, amount)) {
    return { success: false, error: 'SIGNATURE_VERIFICATION_FAILED' };
  }

  // Atomic lock acquisition: Set if Not Exists with short TTL (e.g., 60s processing lock)
  const lockKey = `idempotency:lock:${session.userId}:${nonce}`;
  const acquired = await redis.set(lockKey, 'IN_FLIGHT', 'EX', 60, 'NX');
  if (!acquired) {
    return { success: false, error: 'MUTATION_ALREADY_IN_PROGRESS_OR_COMPLETED' };
  }

  try {
    await db.$transaction(async (tx) => {
      await tx.account.decrement({ where: { userId: session.userId }, data: { balance: amount } });
      await tx.account.increment({ where: { userId: recipientId }, data: { balance: amount } });
      await tx.mutationLog.create({
        data: { nonce, userId: session.userId, action: 'TRANSFER', amount, processedAt: new Date() }
      });
    });

    // Persist completed status with extended retention to permanently prevent replays
    await redis.set(lockKey, 'COMPLETED', 'EX', 86400);
    return { success: true };
  } catch (error) {
    await redis.del(lockKey); // Release lock for genuine network retries on systemic failure
    return { success: false, error: 'TRANSACTION_EXECUTION_FAILED' };
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React 19 Server Actions Cryptographic Nonce & Mutation Idempotency Boundary

React 19 Server Actions Cryptographic Nonce & Mutation Idempotency Boundary defines an industrial-grade behavioral standard for frontend engineering. Mandates cryptographically verifiable, single-use idempotency nonces across all stateful React 19 Server Actions. Defeats replay attacks, eliminates duplicate mutations during optimistic streaming retries, and prevents cross-site state injection in multi-step transitions. 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: Unbounded Server Action Invocations Permitting Replay Exploits and Concurrent Double-Mutation Execution 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 DriftUnbounded Server Action Invocations Permitting Replay Exploits and Concurrent Double-Mutation ExecutionCritical
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 generate an ephemeral, cryptographically secure idempotency nonce on the client or session boundary prior to dispatching stateful Server Actions.

Engineers MUST generate an ephemeral, cryptographically secure idempotency nonce on the client or session boundary prior to dispatching stateful Server Actions.

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 client-side button disabling or local state flags to prevent duplicate Server Action dispatches or network replay attacks.

Engineers MUST NOT rely on client-side button disabling or local state flags to prevent duplicate Server Action dispatches or network replay 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.
3

Server Actions MUST atomically verify, claim, and lock the mutation nonce via an ACID transaction or atomic distributed cache operation (e.g., Redis SETNX with TTL) before applying domain side-effects.

Server Actions MUST atomically verify, claim, and lock the mutation nonce via an ACID transaction or atomic distributed cache operation (e.g., Redis SETNX with TTL) before applying domain side-effects.

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

Optimistic UI updates orchestrated via `useOptimistic` or `useActionState` MUST bind transition states to the deterministic nonce to guarantee predictable rollbacks upon concurrent conflicts or replay rejections.

Optimistic UI updates orchestrated via `useOptimistic` or `useActionState` MUST bind transition states to the deterministic nonce to guarantee predictable rollbacks upon concurrent conflicts or replay rejections.

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

Server Actions MUST cryptographically bind the action payload and user session identifier to the nonce digest to defeat cross-session state injection and transaction parameter tampering.

Server Actions MUST cryptographically bind the action payload and user session identifier to the nonce digest to defeat cross-session state injection and transaction parameter tampering.

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 React 19 Server Actions Cryptographic Nonce & Mutation Idempotency Boundary critical for AI coding assistants?

Mandates cryptographically verifiable, single-use idempotency nonces across all stateful React 19 Server Actions. Defeats replay attacks, eliminates duplicate mutations during optimistic streaming retries, and prevents cross-site state injection in multi-step transitions. 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 (Unbounded Server Action Invocations Permitting Replay Exploits and Concurrent Double-Mutation Execution) 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.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

React