This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: nextjs-15-server-actions-crypto-taint-boundary

Next.js 15 Server Actions Cryptographic Token & Tainted Record Boundary

Enforces strict cryptographic verification of Server Action payloads and guarantees zero data leakage across the React Flight boundary using React 19 taint APIs. Prevents client-side parameter tampering on server actions and accidental serialization of server-only secrets into React Server Component (RSC) streams.

Prohibited Anti-Pattern: Trusting unverified client-supplied identifiers in Server Actions and serializing raw database/secret objects across the Flight RPC boundary

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 Server Actions Cryptographic Token & Tainted Record Boundary - Enforces strict cryptographic verification of Server Action payloads and guarantees zero data leakage across the React Flight boundary using React 19 taint APIs. Prevents client-side parameter tampering on server actions and accidental serialization of server-only secrets into React Server Component (RSC) streams.
globs: src/**/*.{ts,tsx}, app/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nextjs-15-server-actions-crypto-taint-boundary"
---

# Next.js 15 Server Actions Cryptographic Token & Tainted Record Boundary

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Trusting unverified client-supplied identifiers in Server Actions and serializing raw database/secret objects across the Flight RPC boundary

## System Constraints
You are a Principal Architect enforcing cryptographic boundaries in Next.js 15 and React 19 applications. You mandate strict verification of client-invoked Server Actions via HMAC/AEAD tokens, enforce 'server-only' isolation, and mandate the use of React taint APIs (experimental_taintUniqueValue, experimental_taintObjectReference) to completely block secret serialization into RSC flight streams.

## Strict Guidelines
- Engineers MUST ALWAYS import 'server-only' at the top of any module containing Server Actions, database adapters, or cryptographic routines.
- Engineers MUST NEVER trust client-supplied contextual identifiers (e.g., accountId, role, price) passed as Server Action arguments; all authorization contexts MUST be derived from cryptographically verified sessions or authenticated HMAC tokens.
- Engineers MUST call `experimental_taintObjectReference` or `experimental_taintUniqueValue` on server-side credentials, API secrets, and sensitive domain records before exposing parent objects to RSC tree boundaries.
- Code MUST validate all Server Action inputs with strict runtime schema parsers (e.g., Zod) and reject unexpected fields before invoking business logic.
- Services MUST generate and verify tamper-resistant cryptographic signatures (e.g., HMAC-SHA256 or AES-256-GCM) whenever state is serialized into hidden form fields or client-bound action closures.
- Components NEVER pass unmasked sensitive server state into client component props or Server Action closure bindings.

## Bad vs Good Implementations
### Server Action Cryptographic Verification and Record Tainting

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Server Action trusts client-provided arguments (targetAccountId and newBalance) without authorization checks, enabling IDOR and parameter tampering. Furthermore, it returns the raw database object directly into the React Server Component Flight payload, risking credential and PII leakage.
```typescript
// BAD: Blindly trusts client-provided userId and balance; exposes untainted secrets to RSC payload
'use server';

import { db } from '@/lib/db';

export async function updateAccountBalance(targetAccountId: string, newBalance: number) {
  // Insecure: Client can tamper with targetAccountId and newBalance arbitrarily
  const updated = await db.account.update({
    where: { id: targetAccountId },
    data: { balance: newBalance },
  });
  // Insecure: Returns raw database object potentially containing internal tokens or PII to RSC flight payload
  return updated;
}
```

#### Production Standard (Correct)
> **Standard**: The secure implementation imports 'server-only', validates input against a strict schema, guarantees session ownership, verifies an HMAC signature against client tampering, taints the raw database record using React's taint API to prevent serialization leaks, and returns only an explicit, sanitized projection.
```typescript
// GOOD: Uses 'server-only', taints sensitive records, and validates cryptographic token boundary
'use server';

import 'server-only';
import { experimental_taintObjectReference } from 'react';
import { z } from 'zod';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { verifyActionHmac } from '@/lib/crypto';

const ActionInputSchema = z.object({
  accountId: z.string().uuid(),
  deltaAmount: z.number().int().finite(),
  tamperProofToken: z.string().min(64),
});

export async function updateAccountBalance(input: z.infer<typeof ActionInputSchema>) {
  const session = await auth();
  if (!session?.userId) {
    throw new Error('UNAUTHORIZED');
  }

  const { accountId, deltaAmount, tamperProofToken } = ActionInputSchema.parse(input);

  // Cryptographically verify that the target account was signed specifically for this session and action
  const isValid = verifyActionHmac({
    payload: `${session.userId}:${accountId}`,
    signature: tamperProofToken,
  });
  if (!isValid) {
    throw new Error('FORBIDDEN_TAMPERING_DETECTED');
  }

  const account = await db.account.update({
    where: { id: accountId, ownerId: session.userId },
    data: { balance: { increment: deltaAmount } },
  });

  // Taint the database record to prevent accidental serialization into flight payload
  experimental_taintObjectReference(
    'Do not pass internal billing records or payment tokens directly to the client.',
    account
  );

  // Return only sanitized, minimal public projections
  return { success: true, balance: account.balance };
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Next.js 15 Server Actions Cryptographic Token & Tainted Record Boundary

Next.js 15 Server Actions Cryptographic Token & Tainted Record Boundary defines an industrial-grade behavioral standard for frontend engineering. Enforces strict cryptographic verification of Server Action payloads and guarantees zero data leakage across the React Flight boundary using React 19 taint APIs. Prevents client-side parameter tampering on server actions and accidental serialization of server-only secrets into React Server Component (RSC) streams. 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: Trusting unverified client-supplied identifiers in Server Actions and serializing raw database/secret objects across the Flight RPC boundary 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 DriftTrusting unverified client-supplied identifiers in Server Actions and serializing raw database/secret objects across the Flight RPC boundaryCritical
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 import 'server-only' at the top of any module containing Server Actions, database adapters, or cryptographic routines.

Engineers MUST ALWAYS import 'server-only' at the top of any module containing Server Actions, database adapters, or cryptographic routines.

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 NEVER trust client-supplied contextual identifiers (e.g., accountId, role, price) passed as Server Action arguments

Engineers MUST NEVER trust client-supplied contextual identifiers (e.g., accountId, role, price) passed as Server Action arguments; all authorization contexts MUST be derived from cryptographically verified sessions or authenticated HMAC tokens.

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

Engineers MUST call `experimental_taintObjectReference` or `experimental_taintUniqueValue` on server-side credentials, API secrets, and sensitive domain records before exposing parent objects to RSC tree boundaries.

Engineers MUST call `experimental_taintObjectReference` or `experimental_taintUniqueValue` on server-side credentials, API secrets, and sensitive domain records before exposing parent objects to RSC tree boundaries.

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

Code MUST validate all Server Action inputs with strict runtime schema parsers (e.g., Zod) and reject unexpected fields before invoking business logic.

Code MUST validate all Server Action inputs with strict runtime schema parsers (e.g., Zod) and reject unexpected fields before invoking business logic.

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

Services MUST generate and verify tamper-resistant cryptographic signatures (e.g., HMAC-SHA256 or AES-256-GCM) whenever state is serialized into hidden form fields or client-bound action closures.

Services MUST generate and verify tamper-resistant cryptographic signatures (e.g., HMAC-SHA256 or AES-256-GCM) whenever state is serialized into hidden form fields or client-bound action closures.

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.
6

Components NEVER pass unmasked sensitive server state into client component props or Server Action closure bindings.

Components NEVER pass unmasked sensitive server state into client component props or Server Action closure bindings.

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 Next.js 15 Server Actions Cryptographic Token & Tainted Record Boundary critical for AI coding assistants?

Enforces strict cryptographic verification of Server Action payloads and guarantees zero data leakage across the React Flight boundary using React 19 taint APIs. Prevents client-side parameter tampering on server actions and accidental serialization of server-only secrets into React Server Component (RSC) streams. 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 (Trusting unverified client-supplied identifiers in Server Actions and serializing raw database/secret objects across the Flight RPC boundary) 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

Next.js