This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: nextjs-15-server-action-origin-shielding

Next.js 15 Server Action Dynamic Host & Cryptographic Origin Attestation Invariant

Next.js 15 Server Actions accept POST dispatches that can become vulnerable to host header poisoning and cross-origin attacks in multi-domain or reverse-proxy topologies if origin validation is unshielded. This rule mandates strict origin verification, forward-header attestation against canonical domain registries, and defense-in-depth runtime assertions using timing-safe comparisons.

Prohibited Anti-Pattern: Executing naked Server Actions without canonical dynamic host validation or relying entirely on unverified proxy-forwarded headers.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 Server Action Dynamic Host & Cryptographic Origin Attestation Invariant - Next.js 15 Server Actions accept POST dispatches that can become vulnerable to host header poisoning and cross-origin attacks in multi-domain or reverse-proxy topologies if origin validation is unshielded. This rule mandates strict origin verification, forward-header attestation against canonical domain registries, and defense-in-depth runtime assertions using timing-safe comparisons.
globs: src/app/**/actions.ts, src/app/**/actions/*.ts, src/actions/**/*.{ts,tsx}, src/server/**/*.{ts,tsx}, next.config.{js,ts,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nextjs-15-server-action-origin-shielding"
---

# Next.js 15 Server Action Dynamic Host & Cryptographic Origin Attestation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Executing naked Server Actions without canonical dynamic host validation or relying entirely on unverified proxy-forwarded headers.

## System Constraints
You are a Principal Software Architect enforcing cryptographic origin shielding and dynamic host attestation for Next.js 15 Server Actions. You must eliminate all vectors of Host Header Poisoning, Cross-Site Request Forgery (CSRF), and unauthorized cross-origin action dispatches. Next.js 15 provides built-in origin checks against Host headers, but when deployed behind multi-region load balancers, CDNs, or reverse proxies with custom routing, headers like 'x-forwarded-host' and 'origin' can fall out of alignment or be spoofed if proxy trust is misconfigured. You must require every Server Action to execute an immutable origin attestation invariant before processing any payload or mutation.

## Strict Guidelines
- Engineers MUST ALWAYS validate incoming 'Origin' and 'Host' (or validated 'X-Forwarded-Host') headers against an immutable domain registry prior to mutation processing.
- Engineers MUST NOT trust 'x-forwarded-host' or 'x-forwarded-proto' without verifying that the request traversed a trusted, authentic reverse proxy boundary.
- Engineers MUST configure 'serverActions.allowedOrigins' inside 'next.config.ts' for every fully qualified domain permitted to dispatch actions across subdomains or multi-tenant origins.
- Code SHOULD enforce origin attestation through a reusable higher-order function or wrapper (e.g., 'createShieldedAction') that intercepts all execution.
- Services MUST employ constant-time comparison via 'crypto.timingSafeEqual' when evaluating origin tokens or cryptographic CSRF double-submit envelopes to prevent side-channel leakage.
- Components NEVER execute Server Actions directly from unvalidated dynamic forms without an established origin attestation pipeline.

## Bad vs Good Implementations
### Naked Server Action without Host/Origin Attestation Behind Proxies

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The action relies entirely on ambient framework checks without validating the resolved Host against canonical trusted origin registries. When deployed behind reverse proxies, CDNs, or split routing topologies, discrepancies in Host/X-Forwarded-Host can permit execution from unintended or cross-tenant origins.
```typescript
'use server';

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

// CRITICAL FLAW: Blindly executes state mutation relying only on ambient framework defaults.
// Behind CDNs/custom reverse proxies with forwarded host header rewrites, this exposes the
// action to unauthorized cross-origin dispatches and host poisoning.
export async function updateOrganizationProfile(formData: FormData) {
  const orgId = formData.get('orgId') as string;
  const name = formData.get('name') as string;

  await db.organization.update({
    where: { id: orgId },
    data: { name },
  });

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

#### Production Standard (Correct)
> **Standard**: Extracts dynamic request headers in Next.js 15, checks Origin against the resolved forward host and a strict canonical domain whitelist, and uses constant-time comparison to prevent side-channel timing leaks before any database write occurs.
```typescript
'use server';

import { headers } from 'next/headers';
import { timingSafeEqual } from 'node:crypto';
import { db } from '@/lib/db';
import { revalidatePath } from 'next/cache';

const CANONICAL_ORIGINS = new Set([
  'https://app.production.domain.com',
  'https://admin.production.domain.com',
]);

function verifyOriginIntegrity(clientOrigin: string | null, resolvedHost: string | null): boolean {
  if (!clientOrigin || !resolvedHost) return false;

  try {
    const originUrl = new URL(clientOrigin);
    const matchesHost = originUrl.host === resolvedHost;
    const isPermitted = CANONICAL_ORIGINS.has(originUrl.origin);

    if (!matchesHost || !isPermitted) return false;

    const originBuffer = Buffer.from(originUrl.origin);
    const expectedBuffer = Buffer.from(clientOrigin);

    return (
      originBuffer.length === expectedBuffer.length &&
      timingSafeEqual(originBuffer, expectedBuffer)
    );
  } catch {
    return false;
  }
}

async function assertTrustedOrigin(): Promise<void> {
  const headerList = await headers();
  const clientOrigin = headerList.get('origin');
  const clientHost = headerList.get('x-forwarded-host') ?? headerList.get('host');

  if (!verifyOriginIntegrity(clientOrigin, clientHost)) {
    throw new Error('Security Violation: Untrusted or mismatched cross-origin action invocation.');
  }
}

export async function updateOrganizationProfile(formData: FormData) {
  await assertTrustedOrigin();

  const orgId = formData.get('orgId') as string;
  const name = formData.get('name') as string;

  await db.organization.update({
    where: { id: orgId },
    data: { name },
  });

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

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 Dynamic Host & Cryptographic Origin Attestation Invariant

Next.js 15 Server Action Dynamic Host & Cryptographic Origin Attestation Invariant defines an industrial-grade behavioral standard for security engineering. Next.js 15 Server Actions accept POST dispatches that can become vulnerable to host header poisoning and cross-origin attacks in multi-domain or reverse-proxy topologies if origin validation is unshielded. This rule mandates strict origin verification, forward-header attestation against canonical domain registries, and defense-in-depth runtime assertions using timing-safe comparisons. 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: Executing naked Server Actions without canonical dynamic host validation or relying entirely on unverified proxy-forwarded headers. 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 DriftExecuting naked Server Actions without canonical dynamic host validation or relying entirely on unverified proxy-forwarded headers.Critical
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 validate incoming 'Origin' and 'Host' (or validated 'X-Forwarded-Host') headers against an immutable domain registry prior to mutation processing.

Engineers MUST ALWAYS validate incoming 'Origin' and 'Host' (or validated 'X-Forwarded-Host') headers against an immutable domain registry prior to mutation processing.

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 trust 'x-forwarded-host' or 'x-forwarded-proto' without verifying that the request traversed a trusted, authentic reverse proxy boundary.

Engineers MUST NOT trust 'x-forwarded-host' or 'x-forwarded-proto' without verifying that the request traversed a trusted, authentic reverse proxy 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 configure 'serverActions.allowedOrigins' inside 'next.config.ts' for every fully qualified domain permitted to dispatch actions across subdomains or multi-tenant origins.

Engineers MUST configure 'serverActions.allowedOrigins' inside 'next.config.ts' for every fully qualified domain permitted to dispatch actions across subdomains or multi-tenant origins.

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 SHOULD enforce origin attestation through a reusable higher-order function or wrapper (e.g., 'createShieldedAction') that intercepts all execution.

Code SHOULD enforce origin attestation through a reusable higher-order function or wrapper (e.g., 'createShieldedAction') that intercepts all execution.

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 employ constant-time comparison via 'crypto.timingSafeEqual' when evaluating origin tokens or cryptographic CSRF double-submit envelopes to prevent side-channel leakage.

Services MUST employ constant-time comparison via 'crypto.timingSafeEqual' when evaluating origin tokens or cryptographic CSRF double-submit envelopes to prevent side-channel leakage.

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 execute Server Actions directly from unvalidated dynamic forms without an established origin attestation pipeline.

Components NEVER execute Server Actions directly from unvalidated dynamic forms without an established origin attestation pipeline.

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 Dynamic Host & Cryptographic Origin Attestation Invariant critical for AI coding assistants?

Next.js 15 Server Actions accept POST dispatches that can become vulnerable to host header poisoning and cross-origin attacks in multi-domain or reverse-proxy topologies if origin validation is unshielded. This rule mandates strict origin verification, forward-header attestation against canonical domain registries, and defense-in-depth runtime assertions using timing-safe comparisons. 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 (Executing naked Server Actions without canonical dynamic host validation or relying entirely on unverified proxy-forwarded headers.) 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

Next.js