This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor7-wkwebview-cookie-storage-isolation

Capacitor 7 WKWebView Cookie Partitioning & Native Storage Isolation Standard

Enforces deterministic authentication persistence and eliminates silent session termination across native-to-web boundaries in Capacitor 7 under iOS 18+ WKWebsiteDataStore partitioning. Guarantees that authentication state does not rely on ambient cookie mirroring across custom schemes and isolated web processes.

Prohibited Anti-Pattern: Relying on ambient document.cookie or implicit WKHTTPCookieStore synchronization across ASWebAuthenticationSession and custom schemes.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 WKWebView Cookie Partitioning & Native Storage Isolation Standard - Enforces deterministic authentication persistence and eliminates silent session termination across native-to-web boundaries in Capacitor 7 under iOS 18+ WKWebsiteDataStore partitioning. Guarantees that authentication state does not rely on ambient cookie mirroring across custom schemes and isolated web processes.
globs: capacitor.config.ts, src/**/*.{ts,tsx}, ios/App/**/*.{swift,m}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-wkwebview-cookie-storage-isolation"
---

# Capacitor 7 WKWebView Cookie Partitioning & Native Storage Isolation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Relying on ambient document.cookie or implicit WKHTTPCookieStore synchronization across ASWebAuthenticationSession and custom schemes.

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 runtime invariants under iOS 18+ WKWebsiteDataStore isolation policies. iOS 18 enforces strict storage partitioning for non-standard schemes (e.g., capacitor://localhost) and isolates WKWebView data from external authentication sessions (ASWebAuthenticationSession, SFSafariViewController). You must reject any architecture relying on ambient document.cookie or browser credential jars across scheme or native boundaries. Require explicit token-based authentication handshakes, persistent secure storage abstractions, and synchronized native HTTP interceptors.

## Strict Guidelines
- Engineers MUST ALWAYS transfer auth state from OAuth/OIDC providers via cryptographic deep link parameters (PKCE code flow) rather than expecting shared cookies from ASWebAuthenticationSession or SFSafariViewController.
- Engineers MUST NOT rely on ambient 'document.cookie' or 'credentials: include' for session persistence across custom app schemes (e.g., 'capacitor://localhost') on iOS 18+.
- Services MUST store session tokens in encrypted storage using '@capacitor/preferences' or a keychain-backed secure storage plugin, rather than LocalStorage or Cookie jars.
- Engineers MUST configure 'CapacitorHttp' in 'capacitor.config.ts' or use explicit HTTP interceptors to attach 'Authorization: Bearer <token>' headers on outgoing requests.
- Services MUST coordinate native app launch and deep link resume events through an atomic token hydration lifecycle before rendering routes or issuing authenticated API requests to prevent 401 race conditions.
- Components NEVER execute network fetches using ambient browser state during native-to-web bridge initialization.

## Bad vs Good Implementations
### Authentication Persistence Across iOS 18+ Isolated Storage Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: iOS 18 partitions WKWebsiteDataStore instances across custom schemes (e.g. capacitor://) and web contexts. ASWebAuthenticationSession cookies do not synchronize with the Capacitor WKWebView cookie store automatically. Standard fetch with credentials: 'include' drops the session, triggering silent auth failure and 401 unauthenticated cascades.
```typescript
import { App } from '@capacitor/app';

// ANTI-PATTERN: Expects ASWebAuthenticationSession or browser cookie to bleed into WKWebView
export function setupAuthListener(): void {
  App.addListener('appUrlOpen', async (event) => {
    if (event.url.includes('auth-callback')) {
      // Assumes ambient session cookie was set by native authentication session
      // Under iOS 18+ WKWebsiteDataStore partitioning, capacitor://localhost does NOT inherit this cookie
      const response = await fetch('https://api.example.com/user/me', {
        credentials: 'include'
      });
      if (!response.ok) {
        console.error('Session dropped: Cookie partition mismatch.');
      }
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly extracts authorization credentials from the deep-link callback, executes token exchange over the native bridge via CapacitorHttp, and stores the resulting token in durable device storage. This decouples authentication from the isolated WKWebsiteDataStore cookie jar, ensuring resilient session state on iOS 18+.
```typescript
import { App, URLOpenListenerEvent } from '@capacitor/app';
import { Preferences } from '@capacitor/preferences';
import { CapacitorHttp, HttpResponse } from '@capacitor/core';

interface UserProfile {
  id: string;
  email: string;
}

const TOKEN_STORAGE_KEY = 'auth_session_token';

export async function handleAuthCallback(event: URLOpenListenerEvent): Promise<UserProfile | null> {
  const url = new URL(event.url);
  if (!url.pathname.includes('auth-callback')) {
    return null;
  }

  // Extract authorization code or ephemeral token explicitly from deep link
  const authCode = url.searchParams.get('code');
  if (!authCode) {
    throw new Error('Authentication callback missing authorization code.');
  }

  // Exchange code via native HTTP bridge to bypass WebKit cookie partition constraints
  const tokenExchangeResponse: HttpResponse = await CapacitorHttp.post({
    url: 'https://api.example.com/oauth/token',
    headers: { 'Content-Type': 'application/json' },
    data: {
      code: authCode,
      grant_type: 'authorization_code',
      client_id: 'mobile-app-client'
    }
  });

  if (tokenExchangeResponse.status !== 200) {
    throw new Error(`Token exchange failed with status ${tokenExchangeResponse.status}`);
  }

  const { access_token }: { access_token: string } = tokenExchangeResponse.data;

  // Persist deterministically in iOS Keychain/Preferences
  await Preferences.set({
    key: TOKEN_STORAGE_KEY,
    value: access_token
  });

  // Query protected endpoint explicitly injecting Bearer credentials
  const profileResponse: HttpResponse = await CapacitorHttp.get({
    url: 'https://api.example.com/user/me',
    headers: {
      'Authorization': `Bearer ${access_token}`,
      'Content-Type': 'application/json'
    }
  });

  return profileResponse.data as UserProfile;
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 WKWebView Cookie Partitioning & Native Storage Isolation Standard

Capacitor 7 WKWebView Cookie Partitioning & Native Storage Isolation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic authentication persistence and eliminates silent session termination across native-to-web boundaries in Capacitor 7 under iOS 18+ WKWebsiteDataStore partitioning. Guarantees that authentication state does not rely on ambient cookie mirroring across custom schemes and isolated web processes. 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: Relying on ambient document.cookie or implicit WKHTTPCookieStore synchronization across ASWebAuthenticationSession and custom schemes. 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 DriftRelying on ambient document.cookie or implicit WKHTTPCookieStore synchronization across ASWebAuthenticationSession and custom schemes.Critical
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 transfer auth state from OAuth/OIDC providers via cryptographic deep link parameters (PKCE code flow) rather than expecting shared cookies from ASWebAuthenticationSession or SFSafariViewController.

Engineers MUST ALWAYS transfer auth state from OAuth/OIDC providers via cryptographic deep link parameters (PKCE code flow) rather than expecting shared cookies from ASWebAuthenticationSession or SFSafariViewController.

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 ambient 'document.cookie' or 'credentials

Engineers MUST NOT rely on ambient 'document.cookie' or 'credentials: include' for session persistence across custom app schemes (e.g., 'capacitor://localhost') on iOS 18+.

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

Services MUST store session tokens in encrypted storage using '@capacitor/preferences' or a keychain-backed secure storage plugin, rather than LocalStorage or Cookie jars.

Services MUST store session tokens in encrypted storage using '@capacitor/preferences' or a keychain-backed secure storage plugin, rather than LocalStorage or Cookie jars.

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

Engineers MUST configure 'CapacitorHttp' in 'capacitor.config.ts' or use explicit HTTP interceptors to attach 'Authorization

Engineers MUST configure 'CapacitorHttp' in 'capacitor.config.ts' or use explicit HTTP interceptors to attach 'Authorization: Bearer <token>' headers on outgoing requests.

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 coordinate native app launch and deep link resume events through an atomic token hydration lifecycle before rendering routes or issuing authenticated API requests to prevent 401 race conditions.

Services MUST coordinate native app launch and deep link resume events through an atomic token hydration lifecycle before rendering routes or issuing authenticated API requests to prevent 401 race conditions.

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 execute network fetches using ambient browser state during native-to-web bridge initialization.

Components NEVER execute network fetches using ambient browser state during native-to-web bridge initialization.

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 Capacitor 7 WKWebView Cookie Partitioning & Native Storage Isolation Standard critical for AI coding assistants?

Enforces deterministic authentication persistence and eliminates silent session termination across native-to-web boundaries in Capacitor 7 under iOS 18+ WKWebsiteDataStore partitioning. Guarantees that authentication state does not rely on ambient cookie mirroring across custom schemes and isolated web processes. 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 (Relying on ambient document.cookie or implicit WKHTTPCookieStore synchronization across ASWebAuthenticationSession and custom schemes.) 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

Capacitor