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

Next.js 15 Server Action Cryptographic Host & Action-ID Binding Standard

Next.js 15 Server Actions expose implicitly addressable HTTP endpoints identified by dynamic action hashes. In multi-tenant and hardened zero-trust environments, actions must not rely solely on ambient cookie transport; they must cryptographically verify that the incoming Host/Origin, authenticated tenant boundary, and target Action ID match a signed, tamper-proof context token to eliminate blind CSRF, proxy-header spoofing, and cross-tenant replay attacks.

Prohibited Anti-Pattern: Ambient Multi-Tenant State Mutation via Unbound Server Actions Without Origin-Tenant-Action Cryptographic Attestation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 Server Action Cryptographic Host & Action-ID Binding Standard - Next.js 15 Server Actions expose implicitly addressable HTTP endpoints identified by dynamic action hashes. In multi-tenant and hardened zero-trust environments, actions must not rely solely on ambient cookie transport; they must cryptographically verify that the incoming Host/Origin, authenticated tenant boundary, and target Action ID match a signed, tamper-proof context token to eliminate blind CSRF, proxy-header spoofing, and cross-tenant replay attacks.
globs: src/app/**/actions.ts, src/actions/**/*.ts, src/lib/actions/**/*.ts, src/app/**/*.tsx
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nextjs15-server-action-cryptographic-origin-binding"
---

# Next.js 15 Server Action Cryptographic Host & Action-ID Binding Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Ambient Multi-Tenant State Mutation via Unbound Server Actions Without Origin-Tenant-Action Cryptographic Attestation

## System Constraints
You are a Principal Security Architect enforcing the Next.js 15 Server Action Cryptographic Host & Action-ID Binding Standard. Mandate that every mutating Server Action enforces strict cryptographic binding between the client-provided invocation token, the resolved tenant host, the caller identity, and the specific Server Action ID. Never permit direct database mutations from ambient session reads without explicit tenant and action validation.

## Strict Guidelines
- Engineers MUST ALWAYS cryptographically verify that the incoming request host matches the caller's tenant context using headers() and crypto.timingSafeEqual or HMAC verification.
- Engineers MUST NOT rely exclusively on standard cookie-based authentication for state-mutating actions without validating that the action was invoked intentionally within the expected tenant host boundary.
- Engineers MUST wrap all public Server Actions in an immutable action pipeline (e.g., createSecureAction) that verifies an ephemeral, origin-bound Action Context Token (ACT).
- Services MUST validate the 'Next-Action' identifier header against expected permitted action descriptors when handling privileged multi-tenant workflows.
- Engineers MUST NOT read mutable tenant identifiers from client-provided arguments; tenant context MUST be derived strictly from verified cryptographic tokens or verified host-to-session bindings.
- Components NEVER render form elements triggering privileged actions without embedding or linking the short-lived action-binding token generated during server rendering.

## Bad vs Good Implementations
### Vulnerable Server Action Vulnerable to Cross-Tenant Invocations and Replay

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The action trusts a client-supplied tenantId, relies solely on an ambient session cookie without checking incoming origin/host alignment, and lacks an Action Context Token (ACT) to tie the specific action execution to the validated tenant runtime.
```typescript
'use server';

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

interface TransferPayload {
  targetAccountId: string;
  amount: number;
  tenantId: string; // Anti-pattern: accepting client-supplied tenant context
}

export async function executeTransfer(payload: TransferPayload) {
  const session = await auth();
  if (!session?.userId) {
    throw new Error('Unauthorized');
  }

  // VULNERABILITY: Blind trust in caller tenantId combined with ambient cookies.
  // An attacker on tenant-a.app.com can trigger this action against tenant-b if
  // user has cross-tenant access or reverse proxy host-header forwarding is misconfigured.
  // No Action-ID verification or Origin/Host cryptographic attestation.
  return await db.transfer.create({
    data: {
      userId: session.userId,
      tenantId: payload.tenantId,
      targetAccount: payload.targetAccountId,
      amount: payload.amount,
    },
  });
}
```

#### Production Standard (Correct)
> **Standard**: The action retrieves the Host and Next-Action headers and validates an ephemeral HMAC/token linking the session, the caller host, the specific action ID, and the validated tenant ID, preventing CSRF, proxy spoofing, and tenant-confusion replays.
```typescript
'use server';

import { headers } from 'next/headers';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { verifyActionContextToken } from '@/lib/security/action-token';

interface TransferPayload {
  targetAccountId: string;
  amount: number;
  actionToken: string; // Cryptographically signed invocation token
}

export async function executeTransfer(payload: TransferPayload) {
  const session = await auth();
  if (!session?.userId) {
    throw new Error('Unauthorized: Missing active session');
  }

  const headerList = await headers();
  const host = headerList.get('host') ?? '';
  const nextActionId = headerList.get('next-action');

  if (!nextActionId) {
    throw new Error('Bad Request: Missing Next-Action identifier');
  }

  // Invariant: Cryptographically verify token matches [userId, tenantId, host, actionId]
  const verification = await verifyActionContextToken({
    token: payload.actionToken,
    expectedUserId: session.userId,
    expectedHost: host,
    expectedActionId: nextActionId,
  });

  if (!verification.isValid) {
    throw new Error(`Security Violation: Action binding failure [${verification.reason}]`);
  }

  // Secure execution guaranteed to be locked to verified tenant and caller domain
  return await db.transfer.create({
    data: {
      userId: session.userId,
      tenantId: verification.claims.tenantId,
      targetAccount: payload.targetAccountId,
      amount: payload.amount,
    },
  });
}
```

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: Next.js 15 Server Action Cryptographic Host & Action-ID Binding Standard

Next.js 15 Server Action Cryptographic Host & Action-ID Binding Standard defines an industrial-grade behavioral standard for frontend engineering. Next.js 15 Server Actions expose implicitly addressable HTTP endpoints identified by dynamic action hashes. In multi-tenant and hardened zero-trust environments, actions must not rely solely on ambient cookie transport; they must cryptographically verify that the incoming Host/Origin, authenticated tenant boundary, and target Action ID match a signed, tamper-proof context token to eliminate blind CSRF, proxy-header spoofing, and cross-tenant replay attacks. 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: Ambient Multi-Tenant State Mutation via Unbound Server Actions Without Origin-Tenant-Action Cryptographic Attestation 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 DriftAmbient Multi-Tenant State Mutation via Unbound Server Actions Without Origin-Tenant-Action Cryptographic AttestationCritical
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 cryptographically verify that the incoming request host matches the caller's tenant context using headers() and crypto.timingSafeEqual or HMAC verification.

Engineers MUST ALWAYS cryptographically verify that the incoming request host matches the caller's tenant context using headers() and crypto.timingSafeEqual or HMAC verification.

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 exclusively on standard cookie-based authentication for state-mutating actions without validating that the action was invoked intentionally within the expected tenant host boundary.

Engineers MUST NOT rely exclusively on standard cookie-based authentication for state-mutating actions without validating that the action was invoked intentionally within the expected tenant host 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

Engineers MUST wrap all public Server Actions in an immutable action pipeline (e.g., createSecureAction) that verifies an ephemeral, origin-bound Action Context Token (ACT).

Engineers MUST wrap all public Server Actions in an immutable action pipeline (e.g., createSecureAction) that verifies an ephemeral, origin-bound Action Context Token (ACT).

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

Services MUST validate the 'Next-Action' identifier header against expected permitted action descriptors when handling privileged multi-tenant workflows.

Services MUST validate the 'Next-Action' identifier header against expected permitted action descriptors when handling privileged multi-tenant workflows.

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

Engineers MUST NOT read mutable tenant identifiers from client-provided arguments

Engineers MUST NOT read mutable tenant identifiers from client-provided arguments; tenant context MUST be derived strictly from verified cryptographic tokens or verified host-to-session 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.
6

Components NEVER render form elements triggering privileged actions without embedding or linking the short-lived action-binding token generated during server rendering.

Components NEVER render form elements triggering privileged actions without embedding or linking the short-lived action-binding token generated during server rendering.

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 Action Cryptographic Host & Action-ID Binding Standard critical for AI coding assistants?

Next.js 15 Server Actions expose implicitly addressable HTTP endpoints identified by dynamic action hashes. In multi-tenant and hardened zero-trust environments, actions must not rely solely on ambient cookie transport; they must cryptographically verify that the incoming Host/Origin, authenticated tenant boundary, and target Action ID match a signed, tamper-proof context token to eliminate blind CSRF, proxy-header spoofing, and cross-tenant replay attacks. 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 (Ambient Multi-Tenant State Mutation via Unbound Server Actions Without Origin-Tenant-Action Cryptographic Attestation) 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