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

React 19 Server Actions: Cryptographic Replay Barrier & Monotonic Token Invariant

Enforces single-use cryptographic idempotency tokens bound to server action payloads in React 19 to neutralize double-submit race conditions and network replay hazards. Protects progressive enhancement forms and direct client RPC invocations by atomically consuming tokens via transactional storage before executing state-changing operations.

Prohibited Anti-Pattern: Naked Server Actions Executing Unchecked State Mutations Subject to Double-Submit and Replay Cascades

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React 19 Server Actions: Cryptographic Replay Barrier & Monotonic Token Invariant - Enforces single-use cryptographic idempotency tokens bound to server action payloads in React 19 to neutralize double-submit race conditions and network replay hazards. Protects progressive enhancement forms and direct client RPC invocations by atomically consuming tokens via transactional storage before executing state-changing operations.
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-action-cryptographic-replay-barrier"
---

# React 19 Server Actions: Cryptographic Replay Barrier & Monotonic Token Invariant

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Naked Server Actions Executing Unchecked State Mutations Subject to Double-Submit and Replay Cascades

## System Constraints
You are a Principal Software Architect enforcing cryptographic replay barriers and strict idempotency for React 19 Server Actions. Mandate that every stateful mutation bound to a Server Action implements a cryptographically signed, single-use monotonic barrier token that is consumed atomically prior to execution.

## Strict Guidelines
- Engineers MUST ALWAYS generate a cryptographically secure, monotonic nonce or HMAC-signed idempotency token when rendering forms or views executing stateful React 19 Server Actions.
- Engineers MUST NOT rely on client-side button disabling (`disabled={isPending}`) as a concurrency or replay security boundary.
- Services MUST atomically claim and consume the idempotency token (e.g., using Redis `SETNX` or an atomic relational database transaction with unique constraints) BEFORE executing any side effect.
- Components NEVER expose unverified raw action endpoints that alter persistent domain state without validating both the authenticated actor session and the one-time action token.
- Code SHOULD gracefully handle duplicate replay submissions by either returning cached deterministic responses or rejecting with an explicit HTTP 409 / state conflict result rather than failing silently or crashing.

## Bad vs Good Implementations
### React 19 Server Action Idempotency Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The server action lacks cryptographic replay prevention and idempotency safeguards. In flaky network conditions or under progressive enhancement (where client JS has not yet hydrated), duplicate form submissions trigger multiple concurrent balance decrements.
```typescript
// app/actions/transfer.ts
'use server';

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

// VULNERABLE: Direct mutation without replay protection or single-use verification.
// Double clicks, network retries, or progressive enhancement re-submissions cause duplicate execution.
export async function executeTransfer(formData: FormData) {
  const recipientId = formData.get('recipientId') as string;
  const amount = Number(formData.get('amount'));

  // Race hazard: Concurrent requests execute multiple times
  await db.account.decrementBalance(amount);
  await db.account.incrementBalance(recipientId, amount);

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

#### Production Standard (Correct)
> **Standard**: Implements a strict cryptographic replay barrier. An HMAC/signed barrier token is extracted, cryptographically verified, and atomically claimed using a monotonic single-use check (Redis NX lock) before any side-effect or transaction begins.
```typescript
// app/actions/transfer.ts
'use server';

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

export async function executeTransfer(prevState: unknown, formData: FormData) {
  const token = formData.get('__action_barrier_token');
  const recipientId = formData.get('recipientId');
  const amount = Number(formData.get('amount'));

  if (typeof token !== 'string' || !recipientId || isNaN(amount) || amount <= 0) {
    return { success: false, error: 'INVALID_PAYLOAD' };
  }

  // 1. Cryptographically verify signature and payload integrity
  const payload = await verifyActionToken(token);
  if (!payload.valid || payload.action !== 'executeTransfer') {
    return { success: false, error: 'FORBIDDEN_REPLAY_DETECTED' };
  }

  // 2. Monotonic single-use lock: atomically claim token with TTL
  const acquired = await redis.set(`barrier:${payload.tokenId}`, 'LOCKED', 'EX', 300, 'NX');
  if (!acquired) {
    return { success: false, error: 'CONCURRENT_MUTATION_REJECTED' };
  }

  // 3. Execute isolated mutation within transaction
  try {
    await db.$transaction(async (tx) => {
      await tx.account.decrementBalance(amount);
      await tx.account.incrementBalance(String(recipientId), amount);
    });
  } catch (error) {
    // Unlock on failure to allow deliberate retry if applicable
    await redis.del(`barrier:${payload.tokenId}`);
    throw error;
  }

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

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: React 19 Server Actions: Cryptographic Replay Barrier & Monotonic Token Invariant

React 19 Server Actions: Cryptographic Replay Barrier & Monotonic Token Invariant defines an industrial-grade behavioral standard for frontend engineering. Enforces single-use cryptographic idempotency tokens bound to server action payloads in React 19 to neutralize double-submit race conditions and network replay hazards. Protects progressive enhancement forms and direct client RPC invocations by atomically consuming tokens via transactional storage before executing state-changing operations. 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: Naked Server Actions Executing Unchecked State Mutations Subject to Double-Submit and Replay Cascades 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 DriftNaked Server Actions Executing Unchecked State Mutations Subject to Double-Submit and Replay CascadesCritical
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 cryptographically secure, monotonic nonce or HMAC-signed idempotency token when rendering forms or views executing stateful React 19 Server Actions.

Engineers MUST ALWAYS generate a cryptographically secure, monotonic nonce or HMAC-signed idempotency token when rendering forms or views executing stateful React 19 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 (`disabled={isPending}`) as a concurrency or replay security boundary.

Engineers MUST NOT rely on client-side button disabling (`disabled={isPending}`) as a concurrency or replay security boundary.

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 atomically claim and consume the idempotency token (e.g., using Redis `SETNX` or an atomic relational database transaction with unique constraints) BEFORE executing any side effect.

Services MUST atomically claim and consume the idempotency token (e.g., using Redis `SETNX` or an atomic relational database transaction with unique constraints) BEFORE executing any side effect.

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 NEVER expose unverified raw action endpoints that alter persistent domain state without validating both the authenticated actor session and the one-time action token.

Components NEVER expose unverified raw action endpoints that alter persistent domain state without validating both the authenticated actor session and the one-time action token.

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

Code SHOULD gracefully handle duplicate replay submissions by either returning cached deterministic responses or rejecting with an explicit HTTP 409 / state conflict result rather than failing silently or crashing.

Code SHOULD gracefully handle duplicate replay submissions by either returning cached deterministic responses or rejecting with an explicit HTTP 409 / state conflict result rather than failing silently or crashing.

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 Replay Barrier & Monotonic Token Invariant critical for AI coding assistants?

Enforces single-use cryptographic idempotency tokens bound to server action payloads in React 19 to neutralize double-submit race conditions and network replay hazards. Protects progressive enhancement forms and direct client RPC invocations by atomically consuming tokens via transactional storage before executing state-changing operations. 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 (Naked Server Actions Executing Unchecked State Mutations Subject to Double-Submit and Replay Cascades) 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