Language detector used in browser environment for i18next internationalization framework
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Comprehensive configuration system for customizing detection behavior, caching strategies, and lookup parameters across all detection methods. The configuration provides fine-grained control over detection order, storage mechanisms, and language processing.
Main configuration interface for the language detector with all available options.
interface DetectorOptions {
/** Order and methods for language detection */
order?: Array<'querystring' | 'cookie' | 'sessionStorage' | 'localStorage' | 'navigator' | 'htmlTag' | string>;
/** Query parameter name for language lookup */
lookupQuerystring?: string;
/** Cookie name for language lookup */
lookupCookie?: string;
/** SessionStorage key for language lookup */
lookupSessionStorage?: string;
/** LocalStorage key for language lookup */
lookupLocalStorage?: string;
/** URL path segment index for language lookup */
lookupFromPathIndex?: number;
/** Subdomain index for language lookup */
lookupFromSubdomainIndex?: number;
/** 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;
/** HTML element for lang attribute lookup (default: document.documentElement) */
htmlTag?: HTMLElement | null;
/** Language code conversion function */
convertDetectedLanguage?: 'Iso15897' | ((lng: string) => string);
}Advanced cookie configuration options for fine-tuned cookie behavior.
interface CookieOptions {
/** Cookie maximum age in seconds */
maxAge?: number;
/** Cookie expiration date */
expires?: Date;
/** HTTP-only cookie flag */
httpOnly?: boolean;
/** Cookie path */
path?: string;
/** Cookie domain */
domain?: string;
/** Secure cookie flag (HTTPS only) */
secure?: boolean;
/** SameSite cookie attribute */
sameSite?: boolean | 'lax' | 'strict' | 'none';
}Usage Examples:
import I18nextBrowserLanguageDetector from "i18next-browser-languagedetector";
// Basic configuration
const detector = new I18nextBrowserLanguageDetector(null, {
order: ['cookie', 'localStorage', 'navigator'],
lookupCookie: 'user_language',
caches: ['localStorage', 'cookie']
});
// Advanced cookie configuration
const detector = new I18nextBrowserLanguageDetector(null, {
order: ['cookie', 'querystring', 'navigator'],
lookupCookie: 'preferred_lang',
cookieMinutes: 60 * 24 * 30, // 30 days
cookieDomain: '.example.com',
cookieOptions: {
secure: true,
sameSite: 'strict',
path: '/'
}
});Controls the sequence and methods used for language detection.
Available Detection Methods:
'querystring' - URL query parameters (e.g., ?lng=en)'cookie' - Browser cookies'localStorage' - Browser localStorage'sessionStorage' - Browser sessionStorage'navigator' - Browser navigator language settings'htmlTag' - HTML lang attribute'path' - URL path segments (custom detector)'subdomain' - Subdomain-based detection (custom detector)// Prioritize query params and cookies over browser settings
const options = {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag']
};
// Server-side friendly configuration (no browser APIs)
const serverOptions = {
order: ['cookie', 'htmlTag'] // Only methods that work server-side
};
// Single-source detection
const simpleOptions = {
order: ['navigator'] // Only use browser language settings
};Customize the parameter names and locations used by each detection method.
const detector = new I18nextBrowserLanguageDetector(null, {
// URL query parameter name
lookupQuerystring: 'lang', // ?lang=en instead of ?lng=en
// Cookie name
lookupCookie: 'app_language', // Custom cookie name
// Storage keys
lookupLocalStorage: 'userLanguage',
lookupSessionStorage: 'sessionLang',
// Path-based detection
lookupFromPathIndex: 0, // /en/home -> 'en' (first segment)
// Subdomain detection
lookupFromSubdomainIndex: 0 // en.example.com -> 'en'
});Note: For backwards compatibility, lookupFromUrlIndex is also supported as an alias for lookupFromPathIndex.
Controls how and where detected languages are stored for persistence across sessions.
// Multiple cache mechanisms
const options = {
caches: ['localStorage', 'cookie'], // Store in both
excludeCacheFor: ['cimode', 'dev'], // Don't cache these languages
// Cache timing
cookieMinutes: 60 * 24 * 365, // 1 year cookie expiration
};
// No caching
const noCacheOptions = {
caches: [] // Don't cache detected languages
};
// Cookie-only caching with domain
const cookieOnlyOptions = {
caches: ['cookie'],
cookieDomain: '.myapp.com', // Share across subdomains
cookieOptions: {
secure: true,
sameSite: 'lax'
}
};Transform detected language codes using built-in converters or custom functions.
// Built-in ISO 15897 conversion (dash to underscore)
// Converts language-REGION format to language_REGION format
const iso15897Options = {
convertDetectedLanguage: 'Iso15897' // en-US -> en_US, zh-CN -> zh_CN
};
// Custom conversion function
const customOptions = {
convertDetectedLanguage: (lng) => {
// Convert to lowercase and remove region codes
return lng.toLowerCase().split('-')[0];
}
};
// Custom mapping function
const mappingOptions = {
convertDetectedLanguage: (lng) => {
const mapping = {
'zh-CN': 'zh-Hans',
'zh-TW': 'zh-Hant',
'en-GB': 'en-UK'
};
return mapping[lng] || lng;
}
};Customize the HTML element used for lang attribute detection.
// Use specific element instead of document.documentElement
const customHtmlOptions = {
htmlTag: document.querySelector('#app'), // Use specific element
};
// Disable HTML tag detection
const noHtmlOptions = {
htmlTag: null // Don't use HTML tag detection
};When no options are provided, the detector uses these defaults:
const defaultOptions = {
order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
lookupSessionStorage: 'i18nextLng',
caches: ['localStorage'],
excludeCacheFor: ['cimode'],
convertDetectedLanguage: (l) => l // Identity function
};Note: If cookie access is not available (throws exception), the 'cookie' method is automatically removed from the default order.
Options are merged using a defaults-based approach where undefined values are filled with defaults:
// Your options
const userOptions = {
order: ['cookie', 'navigator'],
lookupCookie: 'my_lang'
// Other options use defaults
};
// Merged with defaults
const finalOptions = {
order: ['cookie', 'navigator'], // Your value
lookupCookie: 'my_lang', // Your value
lookupQuerystring: 'lng', // Default value
lookupLocalStorage: 'i18nextLng', // Default value
// ... other defaults
};