CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-i18next-browser-languagedetector

Language detector used in browser environment for i18next internationalization framework

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

detection.mddocs/

Language Detection

Core language detection functionality that automatically identifies user's preferred language from multiple browser sources. The detection system processes configured sources in order until a language is found, supporting both single language detection and language arrays for i18next compatibility.

Capabilities

Main Detector Class

Creates a new language detector instance that implements the i18next LanguageDetectorModule interface.

/**
 * Browser-based language detector for i18next
 * @param services - i18next services object (optional)
 * @param options - Detection configuration options
 */
class I18nextBrowserLanguageDetector {
  constructor(services?: any, options?: DetectorOptions);
  
  /** Plugin type identifier for i18next */
  type: 'languageDetector';
  
  /** Registry of available detector modules */
  detectors: { [key: string]: any };
  
  /** i18next services object */
  services: any;
  
  /** i18next configuration options */
  i18nOptions: any;
}

Usage Examples:

import I18nextBrowserLanguageDetector from "i18next-browser-languagedetector";

// Basic initialization
const detector = new I18nextBrowserLanguageDetector();

// With options
const detector = new I18nextBrowserLanguageDetector(null, {
  order: ['cookie', 'localStorage', 'navigator'],
  lookupCookie: 'preferred_language',
  caches: ['localStorage']
});

// With i18next services
import i18next from "i18next";
const detector = new I18nextBrowserLanguageDetector(i18next.services, options);

Initialization

Initializes the detector with services and options, setting up all built-in detector modules.

/**
 * Initialize detector with services and options
 * @param services - i18next services object (optional)
 * @param options - Detection configuration options
 * @param i18nOptions - i18next configuration options
 */
init(services?: any, options?: DetectorOptions, i18nOptions?: any): void;

Usage Examples:

// Initialize with options
detector.init(null, {
  order: ['querystring', 'cookie', 'navigator'],
  lookupQuerystring: 'lang',
  cookieMinutes: 60
});

// Initialize with i18next services
detector.init(i18next.services, options, {
  fallbackLng: 'en',
  debug: true
});

Language Detection

Detects user's preferred language using the configured detection methods in order.

/**
 * Detect user's preferred language from configured sources
 * @param detectionOrder - Override default detection order (optional)
 * @returns Detected language code(s) or undefined if none found
 */
detect(detectionOrder?: DetectorOptions['order']): string | string[] | undefined;

Usage Examples:

// Use configured detection order
const language = detector.detect();
console.log(language); // "en-US" or ["en-US", "en"] or undefined

// Override detection order
const language = detector.detect(['navigator', 'htmlTag']);

// Handle different return types
const detected = detector.detect();
if (Array.isArray(detected)) {
  console.log('Multiple languages detected:', detected);
} else if (detected) {
  console.log('Single language detected:', detected);
} else {
  console.log('No language detected');
}

Custom Detector Addition

Adds custom detector implementations to the detection chain.

/**
 * Add a custom detector to the detector registry
 * @param detector - Custom detector implementation
 * @returns Self for method chaining
 */
addDetector(detector: CustomDetector): I18nextBrowserLanguageDetector;

interface CustomDetector {
  /** Unique name for the detector */
  name: string;
  
  /** Language detection implementation */
  lookup(options: DetectorOptions): string | string[] | undefined;
  
  /** Optional caching implementation */
  cacheUserLanguage?(lng: string, options: DetectorOptions): void;
}

Usage Examples:

// Custom detector for user preferences API
const preferencesDetector = {
  name: 'userPreferences',
  
  lookup(options) {
    // Custom detection logic
    const userSettings = getUserSettings(); // Your custom function
    return userSettings?.language;
  },
  
  cacheUserLanguage(lng, options) {
    // Custom caching logic
    saveUserSettings({ language: lng }); // Your custom function
  }
};

// Add to detector
detector.addDetector(preferencesDetector);

// Use in detection order
detector.init(null, {
  order: ['userPreferences', 'cookie', 'navigator']
});

Detection Chain Behavior

The detection system processes sources in the configured order:

  1. Sequential Processing: Each detector in the order array is called until one returns a result
  2. Result Types: Detectors can return string, string[], or undefined
  3. Language Conversion: Results are processed through convertDetectedLanguage if configured
  4. i18next Compatibility: Returns array format for i18next v19.5.0+, single string for older versions
  5. Fallback: Returns null or undefined if no language is detected

Built-in Detection Order:

Default order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag']

When cookies are not available, cookie detection is automatically removed from the order.

Error Handling

The detection system is designed to be resilient:

  • Browser Compatibility: Gracefully handles missing browser APIs
  • Storage Availability: Automatically detects and skips unavailable storage mechanisms
  • Cookie Access: Safely handles environments where document.cookie throws exceptions
  • DOM Access: Safely handles server-side rendering environments where document is undefined

docs

caching.md

configuration.md

detection.md

detectors.md

index.md

tile.json