This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: nextjs-15-client-segment-cache-crypto-tag-pinning

Next.js 15 Client Router Segment Cache Cryptographic Tag Pinning Standard

Enforces cryptographic deployment revision tag pinning for Next.js 15 App Router client-side segment cache payloads during zero-downtime rolling deployments. Prevents hydration skew, chunk execution crashes, and stale React Server Component (RSC) tree stitching by deterministically invalidating client router memory upon server release divergence.

Prohibited Anti-Pattern: Unpinned Client Segment Prefetching Causing Hydration Skew and Action Desync During Rolling Deploys

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 Client Router Segment Cache Cryptographic Tag Pinning Standard - Enforces cryptographic deployment revision tag pinning for Next.js 15 App Router client-side segment cache payloads during zero-downtime rolling deployments. Prevents hydration skew, chunk execution crashes, and stale React Server Component (RSC) tree stitching by deterministically invalidating client router memory upon server release divergence.
globs: next.config.{js,ts,mjs}, src/middleware.{ts,js}, src/app/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nextjs-15-client-segment-cache-crypto-tag-pinning"
---

# Next.js 15 Client Router Segment Cache Cryptographic Tag Pinning Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unpinned Client Segment Prefetching Causing Hydration Skew and Action Desync During Rolling Deploys

## System Constraints
You are a Principal Software Architect enforcing zero-downtime client-state integrity in Next.js 15. Mandate cryptographic revision binding for RSC segment cache entries, deterministic router cache invalidation across rolling canary nodes, and strict guardrails against mismatched Server Action build IDs.

## Strict Guidelines
- Engineers MUST ALWAYS configure `deploymentId` inside `next.config.ts` bound to an immutable commit hash or cryptographic release tag (e.g., `process.env.NEXT_DEPLOYMENT_ID`).
- Engineers MUST configure Next.js 15 client router `staleTimes` to zero or strict bounded windows for dynamic paths to prevent stale client segment stitching during rolling deploys.
- Middleware MUST intercept RSC requests (`_rsc`) and validate incoming revision tokens against the active server instance deployment ID, returning a strict cache-busting header or reload trigger on drift.
- Components NEVER store or reuse prefetched Server Action action IDs across segment cache updates without validating build revision consistency.
- Client boundary wrappers MUST listen for RSC fetch errors with deployment hash mismatches and trigger a hard document reload (`window.location.reload()`) instead of falling into an unrecoverable React error boundary.

## Bad vs Good Implementations
### Configuring Next.js 15 Deployment Tag Pinning and Stale Times

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Without an explicit deploymentId, client-side RSC segment caches persist across rolling deployments. If Node A and Node B run different builds simultaneously, the client stitches segments from Node A with assets from Node B, leading to missing chunk errors and Server Action 404s.
```typescript
// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  // Default router cache settings allow client segments to persist
  // across multi-node canary rollouts without revision verification.
  experimental: {
    // Missing deploymentId configuration
  },
};

export default nextConfig;
```

#### Production Standard (Correct)
> **Standard**: Declaring `deploymentId` enforces Next.js 15 to append cryptographic revision query parameters to all RSC and static asset fetches. Setting dynamic `staleTimes` to 0 prevents clients from caching transient segments across rolling cluster boundaries.
```typescript
// next.config.ts
import type { NextConfig } from 'next';

const deploymentId = process.env.NEXT_DEPLOYMENT_ID || process.env.VERCEL_GIT_COMMIT_SHA;
if (!deploymentId && process.env.NODE_ENV === 'production') {
  throw new Error('FATAL: NEXT_DEPLOYMENT_ID must be pinned during production builds.');
}

const nextConfig: NextConfig = {
  deploymentId,
  experimental: {
    staleTimes: {
      dynamic: 0, // Invalidate dynamic route segments immediately
      static: 180, // Bound static segments to max 3 minutes
    },
  },
};

export default nextConfig;
```

### Middleware Cryptographic Tag Verification and Segment Invalidation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Lacks revision drift detection. If an RSC payload is requested by a client whose cache was seeded by an older deployment, the middleware serves hybrid segments, leading to hydration crashes.
```typescript
// src/middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/request';

export function middleware(request: NextRequest) {
  // Blindly passes RSC segment requests through without validating
  // whether the client's cached segment aligns with the serving instance build.
  return NextResponse.next();
}
```

#### Production Standard (Correct)
> **Standard**: Middleware actively intercepts RSC requests and inspects deployment tags. When deployment drift is detected, it terminates the request with a 409 Conflict, instructing client error boundaries to perform a clean document reload rather than rendering a corrupted layout segment.
```typescript
// src/middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const SERVER_DEPLOYMENT_TAG = process.env.NEXT_DEPLOYMENT_ID || 'local-dev';

export function middleware(request: NextRequest) {
  const clientDeploymentTag = request.headers.get('x-deployment-id') || request.nextUrl.searchParams.get('dpl');
  const isRscRequest = request.headers.get('rsc') === '1' || request.nextUrl.searchParams.has('_rsc');

  // Detect deployment drift on client router segment prefetch
  if (isRscRequest && clientDeploymentTag && clientDeploymentTag !== SERVER_DEPLOYMENT_TAG) {
    const response = new NextResponse(null, {
      status: 409,
      statusText: 'Deployment Skew Detected',
      headers: {
        'x-deployment-skew': 'true',
        'x-server-deployment-id': SERVER_DEPLOYMENT_TAG,
        'Cache-Control': 'no-store, no-cache, must-revalidate',
      },
    });
    return response;
  }

  const response = NextResponse.next();
  response.headers.set('x-deployment-id', SERVER_DEPLOYMENT_TAG);
  return response;
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Next.js 15 Client Router Segment Cache Cryptographic Tag Pinning Standard

Next.js 15 Client Router Segment Cache Cryptographic Tag Pinning Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces cryptographic deployment revision tag pinning for Next.js 15 App Router client-side segment cache payloads during zero-downtime rolling deployments. Prevents hydration skew, chunk execution crashes, and stale React Server Component (RSC) tree stitching by deterministically invalidating client router memory upon server release divergence. 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: Unpinned Client Segment Prefetching Causing Hydration Skew and Action Desync During Rolling Deploys 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 DriftUnpinned Client Segment Prefetching Causing Hydration Skew and Action Desync During Rolling DeploysCritical
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 configure `deploymentId` inside `next.config.ts` bound to an immutable commit hash or cryptographic release tag (e.g., `process.env.NEXT_DEPLOYMENT_ID`).

Engineers MUST ALWAYS configure `deploymentId` inside `next.config.ts` bound to an immutable commit hash or cryptographic release tag (e.g., `process.env.NEXT_DEPLOYMENT_ID`).

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 configure Next.js 15 client router `staleTimes` to zero or strict bounded windows for dynamic paths to prevent stale client segment stitching during rolling deploys.

Engineers MUST configure Next.js 15 client router `staleTimes` to zero or strict bounded windows for dynamic paths to prevent stale client segment stitching during rolling deploys.

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

Middleware MUST intercept RSC requests (`_rsc`) and validate incoming revision tokens against the active server instance deployment ID, returning a strict cache-busting header or reload trigger on drift.

Middleware MUST intercept RSC requests (`_rsc`) and validate incoming revision tokens against the active server instance deployment ID, returning a strict cache-busting header or reload trigger on drift.

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 store or reuse prefetched Server Action action IDs across segment cache updates without validating build revision consistency.

Components NEVER store or reuse prefetched Server Action action IDs across segment cache updates without validating build revision consistency.

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

Client boundary wrappers MUST listen for RSC fetch errors with deployment hash mismatches and trigger a hard document reload (`window.location.reload()`) instead of falling into an unrecoverable React error boundary.

Client boundary wrappers MUST listen for RSC fetch errors with deployment hash mismatches and trigger a hard document reload (`window.location.reload()`) instead of falling into an unrecoverable React error 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.
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 Client Router Segment Cache Cryptographic Tag Pinning Standard critical for AI coding assistants?

Enforces cryptographic deployment revision tag pinning for Next.js 15 App Router client-side segment cache payloads during zero-downtime rolling deployments. Prevents hydration skew, chunk execution crashes, and stale React Server Component (RSC) tree stitching by deterministically invalidating client router memory upon server release divergence. 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 (Unpinned Client Segment Prefetching Causing Hydration Skew and Action Desync During Rolling Deploys) 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