This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: react-native-mmkv-synchronous-sandboxing-standard

React Native MMKV Instance Sandboxing, Synchronous JSI Access, and Encryption Invariants

Enforces synchronous JSI read/write operations and strict multi-instance sandboxing with hardware-keystore-backed encryption for react-native-mmkv. Prohibits wrapping MMKV calls in asynchronous microtasks, hardcoding cryptographic keys, and sharing a single un-namespaced storage instance across multi-tenant or domain boundaries.

Prohibited Anti-Pattern: Treating MMKV as Asynchronous Storage, Using Default Global Instances Across Tenants, and Hardcoding Encryption Keys

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native MMKV Instance Sandboxing, Synchronous JSI Access, and Encryption Invariants - Enforces synchronous JSI read/write operations and strict multi-instance sandboxing with hardware-keystore-backed encryption for react-native-mmkv. Prohibits wrapping MMKV calls in asynchronous microtasks, hardcoding cryptographic keys, and sharing a single un-namespaced storage instance across multi-tenant or domain boundaries.
globs: src/**/*.{ts,tsx}, packages/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-mmkv-synchronous-sandboxing-standard"
---

# React Native MMKV Instance Sandboxing, Synchronous JSI Access, and Encryption Invariants

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Treating MMKV as Asynchronous Storage, Using Default Global Instances Across Tenants, and Hardcoding Encryption Keys

## System Constraints
You are a Principal Mobile Architect enforcing strict react-native-mmkv storage practices. Mandate synchronous JSI execution, hardware-backed instance encryption, and strict domain sandboxing.

## Strict Guidelines
- Engineers MUST ALWAYS leverage direct synchronous JSI operations for MMKV reads and writes, never wrapping MMKV method calls in async/await, Promises, or deferring to macrotasks.
- Engineers MUST instantiate sandboxed MMKV instances using explicit 'id' and 'path' configurations tailored to specific domains (e.g., auth, cache, user-preferences, tenant-id) rather than mutating a shared global instance.
- Engineers MUST retrieve MMKV encryption keys exclusively from secure hardware enclaves (iOS Keychain / Android Keystore via secure storage primitives) and MUST NEVER hardcode, commit, or derive keys from client-side public secrets.
- Code SHOULD validate and parse stored complex objects through static schema boundaries (e.g., Zod or TypeBox) immediately upon synchronous retrieval, preventing uncaught runtime JSON deserialization bugs.
- Services MUST execute `.clearAll()` or delete domain-specific MMKV instances upon user logout or session revocation to eliminate persistent data leakage in multi-tenant workflows.
- Components NEVER directly invoke MMKV instances; access must be mediated through strongly-typed state adapters, dedicated repository hooks, or reactive observers such as 'useMMKVString' / 'useMMKVBoolean'.

## Bad vs Good Implementations
### Anti-Pattern: Async-wrapped Global MMKV with Hardcoded Keys

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Wraps synchronous C++ JSI bindings in synthetic async Promises, incurring unnecessary microtask loop scheduling overhead. It hardcodes a static encryption key in client source code and mixes disparate domains in an un-sandboxed global instance without schema validation.
```typescript
import { MMKV } from 'react-native-mmkv';

// Anti-pattern: Shared global unpartitioned instance with hardcoded encryption key
export const globalStorage = new MMKV({
  id: 'global-app-storage',
  encryptionKey: 'my-hardcoded-secret-key-123'
});

// Anti-pattern: Unnecessary asynchronous wrapper around synchronous JSI bindings
export async function saveUserSession(userData: { id: string; email: string }) {
  return new Promise((resolve) => {
    globalStorage.set('user_session', JSON.stringify(userData));
    resolve(true);
  });
}

export async function getUserSession() {
  const raw = globalStorage.getString('user_session');
  // Anti-pattern: Unsafe cast without runtime schema validation
  return raw ? JSON.parse(raw) : null;
}
```

#### Production Standard (Correct)
> **Standard**: Leverages synchronous JSI execution with zero async overhead. The storage instance is strictly sandboxed per-user with isolated file paths, accepts dynamic hardware-secured encryption keys, validates all I/O via Zod schemas, and provides deterministic session cleanup.
```typescript
import { MMKV } from 'react-native-mmkv';
import { z } from 'zod';

const UserSessionSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  tokenExpiresAt: z.number()
});
export type UserSession = z.infer<typeof UserSessionSchema>;

interface MMKVStorageConfig {
  userId: string;
  encryptionKey: string; // Dynamically provisioned from KeyStore/Keychain
}

// Factory producing sandboxed, cryptographically isolated instances
export function createUserStorage({ userId, encryptionKey }: MMKVStorageConfig): MMKV {
  return new MMKV({
    id: `user-sandbox-${userId}`,
    path: `secure-storage/${userId}`,
    encryptionKey
  });
}

export class UserSessionRepository {
  private static readonly SESSION_KEY = 'session_payload';

  constructor(private readonly storage: MMKV) {}

  // Zero-asynchronous overhead: pure synchronous JSI invocation
  public getSession(): UserSession | null {
    const serialized = this.storage.getString(UserSessionRepository.SESSION_KEY);
    if (!serialized) return null;

    try {
      const parsed = JSON.parse(serialized);
      return UserSessionSchema.parse(parsed);
    } catch {
      this.storage.delete(UserSessionRepository.SESSION_KEY);
      return null;
    }
  }

  public setSession(session: UserSession): void {
    UserSessionSchema.parse(session);
    this.storage.set(UserSessionRepository.SESSION_KEY, JSON.stringify(session));
  }

  public purge(): void {
    this.storage.clearAll();
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native MMKV Instance Sandboxing, Synchronous JSI Access, and Encryption Invariants

React Native MMKV Instance Sandboxing, Synchronous JSI Access, and Encryption Invariants defines an industrial-grade behavioral standard for mobile engineering. Enforces synchronous JSI read/write operations and strict multi-instance sandboxing with hardware-keystore-backed encryption for react-native-mmkv. Prohibits wrapping MMKV calls in asynchronous microtasks, hardcoding cryptographic keys, and sharing a single un-namespaced storage instance across multi-tenant or domain boundaries. 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: Treating MMKV as Asynchronous Storage, Using Default Global Instances Across Tenants, and Hardcoding Encryption Keys 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 DriftTreating MMKV as Asynchronous Storage, Using Default Global Instances Across Tenants, and Hardcoding Encryption KeysCritical
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 leverage direct synchronous JSI operations for MMKV reads and writes, never wrapping MMKV method calls in async/await, Promises, or deferring to macrotasks.

Engineers MUST ALWAYS leverage direct synchronous JSI operations for MMKV reads and writes, never wrapping MMKV method calls in async/await, Promises, or deferring to macrotasks.

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 instantiate sandboxed MMKV instances using explicit 'id' and 'path' configurations tailored to specific domains (e.g., auth, cache, user-preferences, tenant-id) rather than mutating a shared global instance.

Engineers MUST instantiate sandboxed MMKV instances using explicit 'id' and 'path' configurations tailored to specific domains (e.g., auth, cache, user-preferences, tenant-id) rather than mutating a shared global instance.

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 retrieve MMKV encryption keys exclusively from secure hardware enclaves (iOS Keychain / Android Keystore via secure storage primitives) and MUST NEVER hardcode, commit, or derive keys from client-side public secrets.

Engineers MUST retrieve MMKV encryption keys exclusively from secure hardware enclaves (iOS Keychain / Android Keystore via secure storage primitives) and MUST NEVER hardcode, commit, or derive keys from client-side public secrets.

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 validate and parse stored complex objects through static schema boundaries (e.g., Zod or TypeBox) immediately upon synchronous retrieval, preventing uncaught runtime JSON deserialization bugs.

Code SHOULD validate and parse stored complex objects through static schema boundaries (e.g., Zod or TypeBox) immediately upon synchronous retrieval, preventing uncaught runtime JSON deserialization bugs.

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 execute `.clearAll()` or delete domain-specific MMKV instances upon user logout or session revocation to eliminate persistent data leakage in multi-tenant workflows.

Services MUST execute `.clearAll()` or delete domain-specific MMKV instances upon user logout or session revocation to eliminate persistent data leakage in multi-tenant workflows.

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 directly invoke MMKV instances

Components NEVER directly invoke MMKV instances; access must be mediated through strongly-typed state adapters, dedicated repository hooks, or reactive observers such as 'useMMKVString' / 'useMMKVBoolean'.

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 React Native MMKV Instance Sandboxing, Synchronous JSI Access, and Encryption Invariants critical for AI coding assistants?

Enforces synchronous JSI read/write operations and strict multi-instance sandboxing with hardware-keystore-backed encryption for react-native-mmkv. Prohibits wrapping MMKV calls in asynchronous microtasks, hardcoding cryptographic keys, and sharing a single un-namespaced storage instance across multi-tenant or domain boundaries. 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 (Treating MMKV as Asynchronous Storage, Using Default Global Instances Across Tenants, and Hardcoding Encryption Keys) 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 MOBILE Rules

View all rules →
1 Rule in Stack

React