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

Next.js 15 'use cache' Cryptographic Tenant-Fenced Tagging Standard

Enforces deterministic, cryptographically signed tenant prefixes on all cache tags generated within Next.js 15 'use cache' scopes. Raw or guessable tenant string interpolations (e.g., 'tenant-123:orders') create cross-tenant cache contamination, tag-purging denial of service, and edge-level data leak risks across shared regional CDN infrastructure.

Prohibited Anti-Pattern: Predictable String Interpolation in Multi-Tenant 'use cache' Tags Causing Edge Cache Contamination

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 'use cache' Cryptographic Tenant-Fenced Tagging Standard - Enforces deterministic, cryptographically signed tenant prefixes on all cache tags generated within Next.js 15 'use cache' scopes. Raw or guessable tenant string interpolations (e.g., 'tenant-123:orders') create cross-tenant cache contamination, tag-purging denial of service, and edge-level data leak risks across shared regional CDN infrastructure.
globs: src/**/*.{ts,tsx}, app/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nextjs-15-use-cache-cryptographic-tenant-tagging"
---

# Next.js 15 'use cache' Cryptographic Tenant-Fenced Tagging Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Predictable String Interpolation in Multi-Tenant 'use cache' Tags Causing Edge Cache Contamination

## System Constraints
You are a Principal Software Architect enforcing the Next.js 15 'use cache' Cryptographic Tenant-Fenced Tagging Standard. You must reject any raw, non-deterministic, or unverified tenant ID interpolation in `cacheTag()` or `revalidateTag()`. Mandate that all cache tags tied to tenant-scoped data derive from a cryptographically signed HMAC or salted hash token using a secure server-side secret.

## Strict Guidelines
- Engineers MUST ALWAYS generate cache tags for tenant-scoped data using a centralized cryptographic helper that computes an HMAC-SHA256 signature over the tenant identifier.
- Engineers MUST NOT concatenate raw, unhashed tenant identifiers (e.g., `cacheTag(`tenant-${id}:data`)`) in any component or function marked with `'use cache'`.
- Code SHOULD include the cryptographic tenant fence as the first positional parameter in `cacheTag()` to ensure deterministic indexing across edge cache key trees.
- Services MUST validate tenant membership against verified session context before issuing signed cache tags or invoking `revalidateTag()` with tenant-fenced signatures.
- Components NEVER expose cryptographic tag generators or the underlying signing keys to client bundles or browser-accessible runtimes.

## Bad vs Good Implementations
### Predictable String Interpolation vs. Cryptographically Signed Tenant Fencing in 'use cache'

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly concatenating the raw tenant ID permits malicious actors or buggy upstream layers to purge neighboring tenant caches via revalidateTag() or trigger key collision exploits on shared regional edge CDN caches.
```typescript
// BAD: Raw tenantId interpolation creates predictable tags and cross-tenant collision/invalidation risks
import { cacheTag } from 'next/dist/server/use-cache/cache-tag';

export async function getTenantInvoices(tenantId: string) {
  'use cache';
  // CRITICAL: Unauthenticated raw tag permits predictable cache key eviction and cross-tenant leaks
  cacheTag(`tenant-${tenantId}`, 'invoices');

  const invoices = await db.invoices.findMany({ where: { tenantId } });
  return invoices;
}
```

#### Production Standard (Correct)
> **Standard**: Derives a deterministic, cryptographically signed tag prefix using HMAC-SHA256. Tenants cannot forge or guess other tenant cache keys, isolating multi-tenant cache life-cycles securely across shared edge caches.
```typescript
// GOOD: Cryptographically signed tenant fence generated via server-only HMAC helper
import 'server-only';
import { cacheTag } from 'next/dist/server/use-cache/cache-tag';
import { createHmac } from 'node:crypto';

function getTenantCacheFence(tenantId: string): string {
  const secret = process.env.TENANT_CACHE_SIGNING_KEY;
  if (!secret) {
    throw new Error('TENANT_CACHE_SIGNING_KEY is not defined in runtime environment.');
  }
  const signature = createHmac('sha256', secret)
    .update(`tenant:${tenantId}`)
    .digest('hex')
    .slice(0, 32);
  return `t_${tenantId}_${signature}`;
}

export async function getTenantInvoices(tenantId: string) {
  'use cache';
  const fence = getTenantCacheFence(tenantId);
  // Deterministically signed tag prevents cross-tenant tag hijacking and eviction attacks
  cacheTag(fence, `${fence}:invoices`);

  const invoices = await db.invoices.findMany({ where: { tenantId } });
  return invoices;
}
```

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' Cryptographic Tenant-Fenced Tagging Standard

Next.js 15 'use cache' Cryptographic Tenant-Fenced Tagging Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic, cryptographically signed tenant prefixes on all cache tags generated within Next.js 15 'use cache' scopes. Raw or guessable tenant string interpolations (e.g., 'tenant-123:orders') create cross-tenant cache contamination, tag-purging denial of service, and edge-level data leak risks across shared regional CDN infrastructure. 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: Predictable String Interpolation in Multi-Tenant 'use cache' Tags Causing Edge Cache Contamination 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 DriftPredictable String Interpolation in Multi-Tenant 'use cache' Tags Causing Edge Cache ContaminationCritical
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 generate cache tags for tenant-scoped data using a centralized cryptographic helper that computes an HMAC-SHA256 signature over the tenant identifier.

Engineers MUST ALWAYS generate cache tags for tenant-scoped data using a centralized cryptographic helper that computes an HMAC-SHA256 signature over the tenant identifier.

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 concatenate raw, unhashed tenant identifiers (e.g., `cacheTag(`tenant-${id}

Engineers MUST NOT concatenate raw, unhashed tenant identifiers (e.g., `cacheTag(`tenant-${id}:data`)`) in any component or function marked with `'use cache'`.

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

Code SHOULD include the cryptographic tenant fence as the first positional parameter in `cacheTag()` to ensure deterministic indexing across edge cache key trees.

Code SHOULD include the cryptographic tenant fence as the first positional parameter in `cacheTag()` to ensure deterministic indexing across edge cache key trees.

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 tenant membership against verified session context before issuing signed cache tags or invoking `revalidateTag()` with tenant-fenced signatures.

Services MUST validate tenant membership against verified session context before issuing signed cache tags or invoking `revalidateTag()` with tenant-fenced signatures.

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 expose cryptographic tag generators or the underlying signing keys to client bundles or browser-accessible runtimes.

Components NEVER expose cryptographic tag generators or the underlying signing keys to client bundles or browser-accessible runtimes.

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' Cryptographic Tenant-Fenced Tagging Standard critical for AI coding assistants?

Enforces deterministic, cryptographically signed tenant prefixes on all cache tags generated within Next.js 15 'use cache' scopes. Raw or guessable tenant string interpolations (e.g., 'tenant-123:orders') create cross-tenant cache contamination, tag-purging denial of service, and edge-level data leak risks across shared regional CDN infrastructure. 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 (Predictable String Interpolation in Multi-Tenant 'use cache' Tags Causing Edge Cache Contamination) 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