This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: nextjs-15-router-cache-stale-time-governance

Next.js 15 Client-Side Router Cache Stale-Time Governance

Next.js 15 changes the default Router Cache staleTimes to 0 seconds for dynamic renders, yet misconfigurations in Link prefetching, unstable cache revalidation, and route-segment configs can re-introduce silent cache persistence or trigger severe server thrashing. This standard strictly governs client-side router cache invalidation, fetch revalidation flags, and explicit staleTimes in next.config.js to eliminate mutated state desynchronization across client navigations.

Prohibited Anti-Pattern: Uncontrolled Client Navigation Cache Retaining Mutated State or Triggering Unchecked Dynamic Request Thrashing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 Client-Side Router Cache Stale-Time Governance - Next.js 15 changes the default Router Cache staleTimes to 0 seconds for dynamic renders, yet misconfigurations in Link prefetching, unstable cache revalidation, and route-segment configs can re-introduce silent cache persistence or trigger severe server thrashing. This standard strictly governs client-side router cache invalidation, fetch revalidation flags, and explicit staleTimes in next.config.js to eliminate mutated state desynchronization across client navigations.
globs: src/**/*.{ts,tsx}, app/**/*.{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-router-cache-stale-time-governance"
---

# Next.js 15 Client-Side Router Cache Stale-Time Governance

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Uncontrolled Client Navigation Cache Retaining Mutated State or Triggering Unchecked Dynamic Request Thrashing

## System Constraints
You are a Principal Engineer enforcing Next.js 15 Client-Side Router Cache Stale-Time Governance. Mandate explicit configuration of router cache staleness, deliberate prefetch behaviors on Link components, deterministic Server Action cache purges with revalidatePath/revalidateTag, and prevent accidental retention of stale data across client-side transitions.

## Strict Guidelines
- Engineers MUST ALWAYS explicitly declare `staleTimes` in `next.config.{js,ts,mjs}` under `experimental.staleTimes` when deviating from the Next.js 15 defaults (dynamic: 0s, static: 5min).
- Engineers MUST NOT rely on client-side router caching to persist dynamic data after mutations; Server Actions performing mutations MUST invoke `revalidatePath` or `revalidateTag` prior to returning.
- Components MUST explicitly specify `prefetch={false}` or `prefetch={undefined}` (default dynamic behavior) on `<Link />` components pointing to volatile, permission-sensitive, or real-time routes to prevent unintended speculative prefetch caching.
- Code MUST use `router.refresh()` or explicit action dispatch when mutating client-side state without a server redirection to force the client router cache to evict the active segment.
- Dynamic Route Segments handling mutable entity records MUST export `export const dynamic = 'force-dynamic'` or use dynamic fetch directives (`cache: 'no-store'`) to ensure staleTimes are evaluated as dynamic routes.

## Bad vs Good Implementations
### Configuring Explicit StaleTimes in next.config.ts

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Implicit configurations without audit can lead to confusion across teams migrating between Next.js versions, or unexpected client cache hit behaviors when prefetch defaults vary between static and dynamic render pipelines.
```typescript
import type { NextConfig } from 'next';

// ANTI-PATTERN: Leaving staleTimes implicit or using legacy 30s/5min expectations
// while relying on uncontrolled prefetch behavior across client routes
const nextConfig: NextConfig = {
  reactStrictMode: true,
};

export default nextConfig;
```

#### Production Standard (Correct)
> **Standard**: Declaring explicit experimental.staleTimes documents and enforces client router cache invalidation semantics, guaranteeing dynamic navigations always re-fetch while static routes remain bounded.
```typescript
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  reactStrictMode: true,
  experimental: {
    // Invariant: Next.js 15 allows granular override of client router cache lifetimes
    staleTimes: {
      dynamic: 0,   // Dynamic segments stay at 0s: always pull fresh state on client navigations
      static: 180, // Explicitly constrain static cache lifespan to 3 minutes max
    },
  },
};

export default nextConfig;
```

### Preventing Stale Read Post-Mutation via Server Action & Link Prefetch

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Aggressive `prefetch={true}` coupled with a raw Server Action that lacks cache revalidation guarantees that `/dashboard/entities` will render stale state from the Router Cache upon navigation.
```typescript
'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { updateEntityStatus } from '@/actions/entity';

export function EntityItem({ id, status }: { id: string; status: string }) {
  const router = useRouter();

  async function handleUpdate() {
    // ANTI-PATTERN: Mutating state on server without triggering router cache invalidation
    await updateEntityStatus(id, 'COMPLETED');
    // Client route cache still holds old RSC payload for dashboard
    router.push('/dashboard/entities');
  }

  return (
    <div>
      {/* Aggressive prefetch on volatile route caches stale pre-mutation state */}
      <Link href="/dashboard/entities" prefetch={true}>
        Back to Entities
      </Link>
      <button onClick={handleUpdate}>Complete</button>
    </div>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Omitting aggressive prefetch and wrapping server actions that invoke `revalidatePath` inside `startTransition` ensures the client Router Cache is purged and reconciled upon transition.
```typescript
'use client';

import Link from 'next/link';
import { useTransition } from 'react';
import { updateEntityStatus } from '@/actions/entity';

export function EntityItem({ id, status }: { id: string; status: string }) {
  const [isPending, startTransition] = useTransition();

  function handleUpdate() {
    startTransition(async () => {
      // Action internally calls revalidatePath('/dashboard/entities')
      await updateEntityStatus(id, 'COMPLETED');
    });
  }

  return (
    <div>
      {/* volatile dashboard route: prefetch set to false to avoid caching pre-mutation views */}
      <Link href="/dashboard/entities" prefetch={false}>
        Back to Entities
      </Link>
      <button onClick={handleUpdate} disabled={isPending}>
        {isPending ? 'Updating...' : 'Complete'}
      </button>
    </div>
  );
}
```

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 Client-Side Router Cache Stale-Time Governance

Next.js 15 Client-Side Router Cache Stale-Time Governance defines an industrial-grade behavioral standard for frontend engineering. Next.js 15 changes the default Router Cache staleTimes to 0 seconds for dynamic renders, yet misconfigurations in Link prefetching, unstable cache revalidation, and route-segment configs can re-introduce silent cache persistence or trigger severe server thrashing. This standard strictly governs client-side router cache invalidation, fetch revalidation flags, and explicit staleTimes in next.config.js to eliminate mutated state desynchronization across client navigations. 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: Uncontrolled Client Navigation Cache Retaining Mutated State or Triggering Unchecked Dynamic Request Thrashing 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 DriftUncontrolled Client Navigation Cache Retaining Mutated State or Triggering Unchecked Dynamic Request ThrashingCritical
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 explicitly declare `staleTimes` in `next.config.{js,ts,mjs}` under `experimental.staleTimes` when deviating from the Next.js 15 defaults (dynamic

Engineers MUST ALWAYS explicitly declare `staleTimes` in `next.config.{js,ts,mjs}` under `experimental.staleTimes` when deviating from the Next.js 15 defaults (dynamic: 0s, static: 5min).

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 router caching to persist dynamic data after mutations

Engineers MUST NOT rely on client-side router caching to persist dynamic data after mutations; Server Actions performing mutations MUST invoke `revalidatePath` or `revalidateTag` prior to returning.

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

Components MUST explicitly specify `prefetch={false}` or `prefetch={undefined}` (default dynamic behavior) on `<Link />` components pointing to volatile, permission-sensitive, or real-time routes to prevent unintended speculative prefetch caching.

Components MUST explicitly specify `prefetch={false}` or `prefetch={undefined}` (default dynamic behavior) on `<Link />` components pointing to volatile, permission-sensitive, or real-time routes to prevent unintended speculative prefetch caching.

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 use `router.refresh()` or explicit action dispatch when mutating client-side state without a server redirection to force the client router cache to evict the active segment.

Code MUST use `router.refresh()` or explicit action dispatch when mutating client-side state without a server redirection to force the client router cache to evict the active segment.

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

Dynamic Route Segments handling mutable entity records MUST export `export const dynamic = 'force-dynamic'` or use dynamic fetch directives (`cache

Dynamic Route Segments handling mutable entity records MUST export `export const dynamic = 'force-dynamic'` or use dynamic fetch directives (`cache: 'no-store'`) to ensure staleTimes are evaluated as dynamic routes.

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-Side Router Cache Stale-Time Governance critical for AI coding assistants?

Next.js 15 changes the default Router Cache staleTimes to 0 seconds for dynamic renders, yet misconfigurations in Link prefetching, unstable cache revalidation, and route-segment configs can re-introduce silent cache persistence or trigger severe server thrashing. This standard strictly governs client-side router cache invalidation, fetch revalidation flags, and explicit staleTimes in next.config.js to eliminate mutated state desynchronization across client navigations. 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 (Uncontrolled Client Navigation Cache Retaining Mutated State or Triggering Unchecked Dynamic Request Thrashing) 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