or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

caching.mdconfiguration.mddetection.mddetectors.mdindex.md
tile.json

caching.mddocs/

Language Caching

Automatic language persistence system that stores detected languages in browser storage mechanisms to maintain user preferences across sessions. The caching system supports multiple storage backends with configurable exclusion rules and expiration settings.

Capabilities

Cache User Language Method

Stores a detected or explicitly set language using configured cache mechanisms.

/**
 * Cache user language in configured storage mechanisms
 * @param lng - Language code to cache
 * @param caches - Override default cache mechanisms (optional)
 */
cacheUserLanguage(lng: string, caches?: string[]): void;

Usage Examples:

import I18nextBrowserLanguageDetector from "i18next-browser-languagedetector";

const detector = new I18nextBrowserLanguageDetector(null, {
  caches: ['localStorage', 'cookie'],
  excludeCacheFor: ['cimode', 'dev']
});

// Cache using configured mechanisms
detector.cacheUserLanguage('en-US');

// Override cache mechanisms for this call
detector.cacheUserLanguage('fr', ['cookie']);

// Will not cache due to exclusion rule
detector.cacheUserLanguage('cimode'); // Excluded language

Cache Configuration

Controls which storage mechanisms are used for caching and which languages are excluded.

interface DetectorOptions {
  /** Cache mechanisms to use for storing detected language */
  caches?: string[];
  
  /** Languages to exclude from caching */
  excludeCacheFor?: string[];
  
  /** Cookie expiration time in minutes (default: 10) */
  cookieMinutes?: number;
  
  /** Domain for cookie storage */
  cookieDomain?: string;
  
  /** Additional cookie configuration options */
  cookieOptions?: CookieOptions;
}

Configuration Examples:

// Multiple cache mechanisms
const multiCacheOptions = {
  caches: ['localStorage', 'sessionStorage', 'cookie'],
  excludeCacheFor: ['cimode', 'test', 'debug']
};

// Cookie-only caching with extended expiration
const cookieOnlyOptions = {
  caches: ['cookie'],
  cookieMinutes: 60 * 24 * 365, // 1 year
  cookieDomain: '.example.com', // Share across subdomains
  cookieOptions: {
    secure: true,
    sameSite: 'strict'
  }
};

// No caching
const noCacheOptions = {
  caches: [] // Disable all caching
};

Available Cache Mechanisms

The caching system supports multiple storage backends, each with different persistence characteristics.

LocalStorage Caching

Persistent storage that survives browser restarts and tab closures.

const localStorageOptions = {
  caches: ['localStorage'],
  lookupLocalStorage: 'user_language' // Custom key name
};

// Cached language persists until:
// - User clears browser data
// - localStorage quota is exceeded
// - Explicit removal by application

SessionStorage Caching

Session-scoped storage that persists only for the current browser tab.

const sessionStorageOptions = {
  caches: ['sessionStorage'],
  lookupSessionStorage: 'session_lang' // Custom key name
};

// Cached language persists until:
// - Browser tab is closed
// - Page is refreshed (in some browsers)
// - Explicit removal by application

Cookie Caching

HTTP cookie storage with configurable expiration and domain settings.

const cookieOptions = {
  caches: ['cookie'],
  lookupCookie: 'app_language',
  cookieMinutes: 60 * 24 * 30, // 30 days
  cookieDomain: '.myapp.com',
  cookieOptions: {
    secure: true, // HTTPS only
    sameSite: 'lax', // Cross-site request handling
    path: '/' // Available on all paths
  }
};

// Cached language persists until:
// - Cookie expiration time reached
// - User clears browser cookies
// - Explicit removal by application

Cache Exclusion Rules

Prevents certain languages from being cached, useful for development modes and special language codes.

const exclusionOptions = {
  caches: ['localStorage', 'cookie'],
  excludeCacheFor: [
    'cimode', // i18next's key-as-value mode
    'dev', // Development mode
    'test', // Test environment
    'debug' // Debug mode
  ]
};

// These calls will not cache anything:
detector.cacheUserLanguage('cimode'); // Excluded
detector.cacheUserLanguage('dev'); // Excluded

// This call will cache normally:
detector.cacheUserLanguage('en-US'); // Not excluded

Automatic Caching

The detection system automatically caches detected languages when caching is enabled.

const detector = new I18nextBrowserLanguageDetector(null, {
  order: ['querystring', 'navigator'],
  caches: ['localStorage']
});

// Automatic caching during detection
const detectedLang = detector.detect(); // e.g., 'en-US'
// Language is automatically cached in localStorage

// Manual caching override
detector.cacheUserLanguage('fr'); // Override detected language

Cache Mechanism Priority

When multiple cache mechanisms are configured, they all store the language independently:

const multiCacheOptions = {
  caches: ['localStorage', 'sessionStorage', 'cookie']
};

detector.cacheUserLanguage('en-US');

// Results in:
// localStorage['i18nextLng'] = 'en-US'
// sessionStorage['i18nextLng'] = 'en-US'  
// document.cookie includes 'i18next=en-US'

Cache and Detection Integration

The caching system integrates seamlessly with the detection order:

const integratedOptions = {
  order: ['querystring', 'cookie', 'localStorage', 'navigator'],
  caches: ['localStorage', 'cookie'],
  lookupCookie: 'lang',
  lookupLocalStorage: 'lang'
};

// Detection flow:
// 1. Check querystring (?lng=fr) -> Found 'fr'
// 2. Cache 'fr' in localStorage and cookie
// 3. Return 'fr'

// Next page load:
// 1. Check querystring -> Not found
// 2. Check cookie -> Found 'fr' (from previous cache)
// 3. Return 'fr'

Error Handling and Availability

The caching system gracefully handles storage unavailability:

// Storage availability is checked before caching
const detector = new I18nextBrowserLanguageDetector(null, {
  caches: ['localStorage', 'sessionStorage', 'cookie']
});

// Automatic fallback:
// - If localStorage throws exception -> skip localStorage caching
// - If sessionStorage throws exception -> skip sessionStorage caching  
// - If cookie access fails -> skip cookie caching
// - Continue with available mechanisms

detector.cacheUserLanguage('en'); // Uses only available mechanisms

Custom Cache Implementation

Custom detectors can implement their own caching logic:

const customDetector = {
  name: 'userProfile',
  
  lookup(options) {
    // Custom lookup logic
    return getUserProfile()?.language;
  },
  
  cacheUserLanguage(lng, options) {
    // Custom caching logic
    updateUserProfile({ language: lng });
    
    // Can also use standard caching
    if (options.caches?.includes('localStorage')) {
      localStorage.setItem(options.lookupLocalStorage || 'i18nextLng', lng);
    }
  }
};

detector.addDetector(customDetector);

Cache Management

Best practices for managing cached languages:

// Clear cached language
detector.cacheUserLanguage(''); // Empty string clears cache

// Reset to browser default
const browserLang = detector.detect(['navigator']);
if (browserLang) {
  const lang = Array.isArray(browserLang) ? browserLang[0] : browserLang;
  detector.cacheUserLanguage(lang);
}

// Conditional caching based on user preferences  
const userWantsToSavePreference = getUserPreference('saveLanguage');
if (userWantsToSavePreference) {
  detector.cacheUserLanguage(detectedLanguage);
}

Cache Persistence Comparison

Cache TypePersistenceScopeServer AccessSize Limit
localStorageUntil clearedOriginNo~5-10MB
sessionStorageCurrent sessionTabNo~5-10MB
cookieUntil expirationDomain/PathYes~4KB

Recommendations:

  • localStorage: Best for long-term user preferences
  • sessionStorage: Good for temporary session state
  • cookie: Required for server-side language detection
  • Multiple: Use combination for redundancy and different access patterns