CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-capacitor--core

Cross-platform runtime library that enables web applications to run natively on iOS, Android, Web, and other platforms with unified JavaScript APIs

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

cookie-management.mddocs/

Cookie Management

Cross-platform cookie management with native implementations and web fallbacks. The cookie management system provides a unified API for handling HTTP cookies across web and native platforms while respecting platform-specific security and privacy requirements.

Capabilities

CapacitorCookies Plugin

Main cookie management plugin providing comprehensive cookie operations across all platforms.

/**
 * Cookie management plugin interface
 */
interface CapacitorCookiesPlugin {
  /** Get cookies for a URL */
  getCookies(options?: GetCookieOptions): Promise<HttpCookieMap>;
  /** Set a cookie */
  setCookie(options: SetCookieOptions): Promise<void>;
  /** Delete a specific cookie */
  deleteCookie(options: DeleteCookieOptions): Promise<void>;
  /** Clear cookies for a URL */
  clearCookies(options: ClearCookieOptions): Promise<void>;
  /** Clear all cookies */
  clearAllCookies(): Promise<void>;
}

Usage Examples:

import { CapacitorCookies } from "@capacitor/core";

// Get all cookies
const cookies = await CapacitorCookies.getCookies();
console.log(cookies); // { sessionId: 'abc123', theme: 'dark' }

// Get cookies for specific URL
const siteCookies = await CapacitorCookies.getCookies({
  url: 'https://example.com',
});

// Set a cookie
await CapacitorCookies.setCookie({
  key: 'sessionId',
  value: 'abc123',
  url: 'https://example.com',
  path: '/',
  expires: new Date(Date.now() + 86400000).toISOString(), // 24 hours
});

// Delete a cookie
await CapacitorCookies.deleteCookie({
  key: 'sessionId',
  url: 'https://example.com',
});

// Clear all cookies for a URL
await CapacitorCookies.clearCookies({
  url: 'https://example.com',
});

// Clear all cookies (use with caution)
await CapacitorCookies.clearAllCookies();

Cookie Operations

Individual cookie management operations with detailed configuration options.

/**
 * Get cookies from the device
 * @param options Optional URL to filter cookies
 * @returns Promise resolving to cookie map
 */
getCookies(options?: GetCookieOptions): Promise<HttpCookieMap>;

/**
 * Set a cookie on the device
 * @param options Cookie configuration
 */
setCookie(options: SetCookieOptions): Promise<void>;

/**
 * Delete a specific cookie
 * @param options Cookie identification options
 */
deleteCookie(options: DeleteCookieOptions): Promise<void>;

/**
 * Clear cookies for a specific URL
 * @param options URL to clear cookies for
 */
clearCookies(options: ClearCookieOptions): Promise<void>;

/**
 * Clear all cookies from the device
 */
clearAllCookies(): Promise<void>;

Cookie Configuration Types

Type definitions for cookie operations and configuration.

/**
 * Cookie map returned by getCookies
 */
interface HttpCookieMap {
  [key: string]: string;
}

/**
 * Options for getting cookies
 */
type GetCookieOptions = {
  /** URL to get cookies for */
  url?: string;
};

/**
 * Options for setting cookies
 */
type SetCookieOptions = {
  /** Cookie name/key */
  key: string;
  /** Cookie value */
  value: string;
  /** URL the cookie applies to */
  url?: string;
  /** Path the cookie applies to */
  path?: string;
  /** Expiration date (ISO string) */
  expires?: string;
};

/**
 * Options for deleting cookies
 */
type DeleteCookieOptions = {
  /** Cookie name/key to delete */
  key: string;
  /** URL the cookie applies to */
  url?: string;
};

/**
 * Options for clearing cookies by URL
 */
type ClearCookieOptions = {
  /** URL to clear cookies for */
  url?: string;
};

Usage Examples:

import { CapacitorCookies } from "@capacitor/core";

// Set session cookie
await CapacitorCookies.setCookie({
  key: 'sessionId',
  value: 'user-123-session',
  url: 'https://myapp.com',
  path: '/',
});

// Set persistent cookie with expiration
const oneWeekFromNow = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
await CapacitorCookies.setCookie({
  key: 'rememberUser',
  value: 'true',
  url: 'https://myapp.com',
  path: '/',
  expires: oneWeekFromNow.toISOString(),
});

// Get cookies for current domain
const currentCookies = await CapacitorCookies.getCookies();
const sessionId = currentCookies['sessionId'];

if (sessionId) {
  console.log('User is logged in');
} else {
  console.log('User needs to log in');
}

// Delete specific cookie
await CapacitorCookies.deleteCookie({
  key: 'temporaryData',
  url: 'https://myapp.com',
});

// Clear all cookies for logout
await CapacitorCookies.clearCookies({
  url: 'https://myapp.com',
});

Cookie Management Patterns

Common patterns for cookie-based session management and user preferences.

Usage Examples:

import { CapacitorCookies } from "@capacitor/core";

// Session management helper
class SessionManager {
  private readonly SESSION_KEY = 'userSession';
  private readonly baseUrl = 'https://myapp.com';

  async setSession(sessionData: { userId: string; token: string; expires: number }) {
    await CapacitorCookies.setCookie({
      key: this.SESSION_KEY,
      value: JSON.stringify(sessionData),
      url: this.baseUrl,
      path: '/',
      expires: new Date(sessionData.expires).toISOString(),
    });
  }

  async getSession(): Promise<{ userId: string; token: string; expires: number } | null> {
    const cookies = await CapacitorCookies.getCookies({
      url: this.baseUrl,
    });

    const sessionCookie = cookies[this.SESSION_KEY];
    if (!sessionCookie) {
      return null;
    }

    try {
      return JSON.parse(sessionCookie);
    } catch {
      // Invalid session data, clear it
      await this.clearSession();
      return null;
    }
  }

  async clearSession() {
    await CapacitorCookies.deleteCookie({
      key: this.SESSION_KEY,
      url: this.baseUrl,
    });
  }

  async isLoggedIn(): Promise<boolean> {
    const session = await this.getSession();
    return session !== null && session.expires > Date.now();
  }
}

// User preferences helper
class PreferencesManager {
  private readonly baseUrl = 'https://myapp.com';

  async setPreference(key: string, value: string, persistent = true) {
    const expires = persistent 
      ? new Date(Date.now() + 365 * 24 * 60 * 60 * 1000) // 1 year
      : undefined;

    await CapacitorCookies.setCookie({
      key: `pref_${key}`,
      value,
      url: this.baseUrl,
      path: '/',
      expires: expires?.toISOString(),
    });
  }

  async getPreference(key: string): Promise<string | null> {
    const cookies = await CapacitorCookies.getCookies({
      url: this.baseUrl,
    });

    return cookies[`pref_${key}`] || null;
  }

  async removePreference(key: string) {
    await CapacitorCookies.deleteCookie({
      key: `pref_${key}`,
      url: this.baseUrl,
    });
  }

  async getAllPreferences(): Promise<Record<string, string>> {
    const cookies = await CapacitorCookies.getCookies({
      url: this.baseUrl,
    });

    const preferences: Record<string, string> = {};
    Object.entries(cookies).forEach(([key, value]) => {
      if (key.startsWith('pref_')) {
        preferences[key.substring(5)] = value;
      }
    });

    return preferences;
  }
}

// Usage examples
const sessionManager = new SessionManager();
const prefsManager = new PreferencesManager();

// Login flow
async function login(userId: string, token: string) {
  const expires = Date.now() + 24 * 60 * 60 * 1000; // 24 hours
  await sessionManager.setSession({ userId, token, expires });
}

// Check authentication
async function checkAuth() {
  const isLoggedIn = await sessionManager.isLoggedIn();
  if (!isLoggedIn) {
    // Redirect to login
    window.location.href = '/login';
  }
}

// Save user preferences
async function saveTheme(theme: 'light' | 'dark') {
  await prefsManager.setPreference('theme', theme);
}

// Load user preferences
async function loadTheme(): Promise<'light' | 'dark'> {
  const theme = await prefsManager.getPreference('theme');
  return (theme as 'light' | 'dark') || 'light';
}

// Logout flow
async function logout() {
  await sessionManager.clearSession();
  // Optionally clear other cookies
  await CapacitorCookies.clearCookies({
    url: 'https://myapp.com',
  });
}

Security Considerations

Important security practices when working with cookies across platforms.

Usage Examples:

import { CapacitorCookies } from "@capacitor/core";

// Secure cookie practices
class SecureCookieManager {
  private readonly baseUrl = 'https://myapp.com'; // Always use HTTPS

  async setSecureCookie(key: string, value: string, options: {
    httpOnly?: boolean;
    secure?: boolean;
    maxAge?: number;
  } = {}) {
    // Note: httpOnly and secure flags are typically set server-side
    // On client-side, we can only set basic properties
    
    const expires = options.maxAge 
      ? new Date(Date.now() + options.maxAge * 1000).toISOString()
      : undefined;

    await CapacitorCookies.setCookie({
      key,
      value,
      url: this.baseUrl,
      path: '/',
      expires,
    });
  }

  async setAuthToken(token: string) {
    // For security, consider storing sensitive tokens in native secure storage
    // instead of cookies when possible
    await this.setSecureCookie('authToken', token, {
      maxAge: 3600, // 1 hour
      secure: true,
      httpOnly: true,
    });
  }

  async clearSensitiveCookies() {
    // Clear authentication-related cookies
    const sensitiveKeys = ['authToken', 'sessionId', 'refreshToken'];
    
    for (const key of sensitiveKeys) {
      try {
        await CapacitorCookies.deleteCookie({
          key,
          url: this.baseUrl,
        });
      } catch (error) {
        console.warn(`Failed to clear cookie ${key}:`, error);
      }
    }
  }

  async validateCookieIntegrity(): Promise<boolean> {
    try {
      const cookies = await CapacitorCookies.getCookies({
        url: this.baseUrl,
      });

      // Check for required cookies
      const requiredCookies = ['sessionId'];
      return requiredCookies.every(key => cookies[key]);
    } catch {
      return false;
    }
  }
}

// Privacy-conscious cookie management
class PrivacyCookieManager {
  async clearTrackingCookies() {
    // Clear common tracking cookie patterns
    const cookies = await CapacitorCookies.getCookies();
    
    const trackingPatterns = [
      '_ga', '_gid', '_gat', // Google Analytics
      '_fbp', '_fbc',        // Facebook
      '__utma', '__utmb',    // Legacy Google Analytics
    ];

    for (const [key] of Object.entries(cookies)) {
      const isTracking = trackingPatterns.some(pattern => 
        key.startsWith(pattern)
      );

      if (isTracking) {
        await CapacitorCookies.deleteCookie({ key });
      }
    }
  }

  async respectUserPrivacyChoice(allowCookies: boolean) {
    if (!allowCookies) {
      // Clear non-essential cookies
      await this.clearTrackingCookies();
      
      // Only keep essential session cookies
      const cookies = await CapacitorCookies.getCookies();
      const essentialKeys = ['sessionId', 'csrfToken'];
      
      for (const [key] of Object.entries(cookies)) {
        if (!essentialKeys.includes(key)) {
          await CapacitorCookies.deleteCookie({ key });
        }
      }
    }
  }
}

Install with Tessl CLI

npx tessl i tessl/npm-capacitor--core

docs

cookie-management.md

http-client.md

index.md

platform-runtime.md

plugin-development.md

webview-management.md

tile.json