This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: nextjs-15-use-cache-tag-swr-boundary-guardrail

Next.js 15 'use cache' Cache-Tag Stale-While-Revalidate Boundary Guardrail

Enforces strict boundary isolation between transactional Server Action writes and edge-cached 'use cache' layout derivations in Next.js 15. Prevents stale read anomalies by requiring deterministic cache tagging, immediate post-mutation tag invalidation, and strict separation of transactional return payloads from eventual edge revalidation.

Prohibited Anti-Pattern: Coupling Server Action Mutations to Un-invalidated 'use cache' Derivations with Inconsistent Read Replicas

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 'use cache' Cache-Tag Stale-While-Revalidate Boundary Guardrail - Enforces strict boundary isolation between transactional Server Action writes and edge-cached 'use cache' layout derivations in Next.js 15. Prevents stale read anomalies by requiring deterministic cache tagging, immediate post-mutation tag invalidation, and strict separation of transactional return payloads from eventual edge revalidation.
globs: app/**/*.{ts,tsx}, src/app/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, src/lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nextjs-15-use-cache-tag-swr-boundary-guardrail"
---

# Next.js 15 'use cache' Cache-Tag Stale-While-Revalidate Boundary Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Coupling Server Action Mutations to Un-invalidated 'use cache' Derivations with Inconsistent Read Replicas

## System Constraints
You are a Principal Software Architect enforcing Next.js 15 'use cache' Cache-Tag Stale-While-Revalidate Boundary Guardrails. Mandate strict isolation between transactional write paths (Server Actions) and edge-cached read derivations ('use cache'). Enforce deterministic cache-tag naming, mandatory revalidation triggers, and prohibit reading cached layout functions within transactional write handlers.

## Strict Guidelines
- Engineers MUST ALWAYS attach deterministic, domain-namespaced cache tags via 'cacheTag' inside any function or component declaring the 'use cache' directive.
- Engineers MUST ALWAYS call 'revalidateTag' inside Server Actions immediately after a successful transactional mutation affecting tagged cached derivations.
- Engineers MUST NOT invoke 'use cache' functions inside Server Actions or transactional mutation pipelines to verify write outcomes.
- Services MUST return authoritative write payloads directly from Server Actions to the caller rather than forcing client components to rely on immediate edge cache re-reads.
- Components NEVER combine user-session-specific state with coarse-grained global 'use cache' tags without including the tenant or user principal in the cache tag hierarchy.

## Bad vs Good Implementations
### Decoupled Server Action Mutation and 'use cache' Query with Tag Invalidation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The 'use cache' function lacks explicit cacheTag identification, making targeted invalidation impossible. The Server Action attempts to query the cached reader function immediately following a write, returning stale-while-revalidate edge data instead of transactional truth.
```typescript
// Anti-pattern: Missing tag correlation and querying cached reads during mutation
import { updateProjectName } from '@/lib/db';

export async function getProjects(tenantId: string) {
  'use cache';
  // Flaw: No deterministic cacheTag declared; implicit edge cache with indeterminate TTL
  const res = await fetch(`https://api.internal/tenants/${tenantId}/projects`);
  return res.json();
}

export async function renameProjectAction(tenantId: string, projectId: string, name: string) {
  'use server';
  await updateProjectName(projectId, name);
  // Flaw: Fails to invalidate cache tags, returns stale data from cached reader
  const refreshed = await getProjects(tenantId);
  return { success: true, projects: refreshed };
}
```

#### Production Standard (Correct)
> **Standard**: Binds the cached derivation to a deterministic cacheTag ('tenant:[id]:projects'). The Server Action executes the mutation against the system of record, explicitly revalidates the cache tag for background edge eviction, and returns the authoritative updated entity directly to avoid race conditions with asynchronous SWR propagation.
```typescript
// Production standard: Strict tag-bound derivation with authoritative server action invalidation
import { unstable_cacheTag as cacheTag, revalidateTag } from 'next/cache';
import { updateProjectNameInDb } from '@/lib/db';
import type { Project } from '@/types/project';

const PROJECT_TAGS = {
  byTenant: (tenantId: string) => `tenant:${tenantId}:projects` as const,
  byId: (projectId: string) => `project:${projectId}` as const,
};

export async function getProjectsByTenant(tenantId: string): Promise<Project[]> {
  'use cache';
  cacheTag(PROJECT_TAGS.byTenant(tenantId));
  
  const res = await fetch(`https://api.internal/tenants/${tenantId}/projects`, {
    headers: { 'X-Tenant-ID': tenantId },
  });
  if (!res.ok) throw new Error('Failed to resolve project derivations');
  return res.json();
}

export async function renameProjectAction(
  tenantId: string,
  projectId: string,
  name: string
): Promise<{ success: true; data: Project }> {
  'use server';
  
  const updatedProject = await updateProjectNameInDb(projectId, name);
  
  // Purge edge SWR cache across all regional nodes
  revalidateTag(PROJECT_TAGS.byTenant(tenantId));
  revalidateTag(PROJECT_TAGS.byId(projectId));
  
  // Return authoritative mutation record directly
  return { success: true, data: updatedProject };
}
```

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 'use cache' Cache-Tag Stale-While-Revalidate Boundary Guardrail

Next.js 15 'use cache' Cache-Tag Stale-While-Revalidate Boundary Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary isolation between transactional Server Action writes and edge-cached 'use cache' layout derivations in Next.js 15. Prevents stale read anomalies by requiring deterministic cache tagging, immediate post-mutation tag invalidation, and strict separation of transactional return payloads from eventual edge revalidation. 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: Coupling Server Action Mutations to Un-invalidated 'use cache' Derivations with Inconsistent Read Replicas 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 DriftCoupling Server Action Mutations to Un-invalidated 'use cache' Derivations with Inconsistent Read ReplicasCritical
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 attach deterministic, domain-namespaced cache tags via 'cacheTag' inside any function or component declaring the 'use cache' directive.

Engineers MUST ALWAYS attach deterministic, domain-namespaced cache tags via 'cacheTag' inside any function or component declaring the 'use cache' directive.

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 ALWAYS call 'revalidateTag' inside Server Actions immediately after a successful transactional mutation affecting tagged cached derivations.

Engineers MUST ALWAYS call 'revalidateTag' inside Server Actions immediately after a successful transactional mutation affecting tagged cached derivations.

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 NOT invoke 'use cache' functions inside Server Actions or transactional mutation pipelines to verify write outcomes.

Engineers MUST NOT invoke 'use cache' functions inside Server Actions or transactional mutation pipelines to verify write outcomes.

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 return authoritative write payloads directly from Server Actions to the caller rather than forcing client components to rely on immediate edge cache re-reads.

Services MUST return authoritative write payloads directly from Server Actions to the caller rather than forcing client components to rely on immediate edge cache re-reads.

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

Components NEVER combine user-session-specific state with coarse-grained global 'use cache' tags without including the tenant or user principal in the cache tag hierarchy.

Components NEVER combine user-session-specific state with coarse-grained global 'use cache' tags without including the tenant or user principal in the cache tag hierarchy.

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 'use cache' Cache-Tag Stale-While-Revalidate Boundary Guardrail critical for AI coding assistants?

Enforces strict boundary isolation between transactional Server Action writes and edge-cached 'use cache' layout derivations in Next.js 15. Prevents stale read anomalies by requiring deterministic cache tagging, immediate post-mutation tag invalidation, and strict separation of transactional return payloads from eventual edge revalidation. 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 (Coupling Server Action Mutations to Un-invalidated 'use cache' Derivations with Inconsistent Read Replicas) 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