or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

backend.mdconfiguration.mdindex.mdrequest.mdutils.md
tile.json

configuration.mddocs/

Configuration

Comprehensive configuration system for customizing HTTP requests, URL paths, data parsing, headers, and backend behavior. All options can be set during i18next initialization or direct backend instantiation.

Capabilities

HttpBackendOptions Interface

Main configuration interface with all available options.

interface HttpBackendOptions {
  loadPath?: LoadPathOption;
  addPath?: AddPathOption;
  parse?(data: string, languages?: string | string[], namespaces?: string | string[]): { [key: string]: any };
  parsePayload?(namespace: string, key: string, fallbackValue?: string): { [key: string]: any };
  parseLoadPayload?(languages: string[], namespaces: string[]): { [key: string]: any } | undefined;
  stringify?(payload: any): string;
  crossDomain?: boolean;
  withCredentials?: boolean;
  overrideMimeType?: boolean;
  request?(options: HttpBackendOptions, url: string, payload: {} | string, callback: RequestCallback): void;
  queryStringParams?: { [key: string]: string };
  customHeaders?: { [key: string]: string } | (() => { [key: string]: string });
  reloadInterval?: false | number;
  requestOptions?: RequestInit | ((payload: {} | string) => RequestInit);
  alternateFetch?: FetchFunction;
}

type RequestCallback = (error: any | undefined | null, response: RequestResponse | undefined | null) => void;

Load Path Configuration

Controls how URLs are built for loading translation resources.

type LoadPathOption = 
  | string 
  | ((lngs: string[], namespaces: string[]) => string) 
  | ((lngs: string[], namespaces: string[]) => Promise<string>);

Default:

'/locales/{{lng}}/{{ns}}.json'

Usage Examples:

// Static path with interpolation
{
  loadPath: '/api/translations/{{lng}}/{{ns}}.json'
}

// Dynamic path function
{
  loadPath: (languages, namespaces) => {
    return `/api/v2/translations/${languages[0]}/${namespaces[0]}`;
  }
}

// Async path function
{
  loadPath: async (languages, namespaces) => {
    const config = await getApiConfig();
    return `${config.baseUrl}/translations/${languages[0]}/${namespaces[0]}`;
  }
}

// Conditional path
{
  loadPath: (languages, namespaces) => {
    if (languages.includes('en')) {
      return '/static/translations/{{lng}}/{{ns}}.json';
    }
    return '/api/translations/{{lng}}/{{ns}}.json';
  }
}

Add Path Configuration

Controls how URLs are built for saving missing translation keys.

type AddPathOption = 
  | string 
  | ((lng: string, namespace: string) => string);

Default:

'/locales/add/{{lng}}/{{ns}}'

Usage Examples:

// Static path
{
  addPath: '/api/translations/save/{{lng}}/{{ns}}'
}

// Dynamic path function
{
  addPath: (language, namespace) => {
    return `/api/translations/${language}/${namespace}/missing`;
  }
}

Data Parsing

Custom functions for parsing loaded data and request payloads.

/**
 * Parse loaded translation data
 * @param data - Raw string data from HTTP response
 * @param languages - Languages being loaded (for context)
 * @param namespaces - Namespaces being loaded (for context)
 * @returns Parsed translation object
 */
parse?(data: string, languages?: string | string[], namespaces?: string | string[]): { [key: string]: any };

/**
 * Parse data before sending via addPath (for saving missing keys)
 * @param namespace - Target namespace
 * @param key - Translation key
 * @param fallbackValue - Default value
 * @returns Request payload object
 */
parsePayload?(namespace: string, key: string, fallbackValue?: string): { [key: string]: any };

/**
 * Parse data before sending via loadPath (enables POST requests)
 * @param languages - Languages being requested
 * @param namespaces - Namespaces being requested
 * @returns Request payload object or undefined for GET requests
 */
parseLoadPayload?(languages: string[], namespaces: string[]): { [key: string]: any } | undefined;

Usage Examples:

import JSON5 from 'json5';
import { parse as parseJSONC } from 'jsonc-parser';

// JSON5 parsing
{
  parse: JSON5.parse
}

// JSONC (JSON with comments) parsing
{
  parse: parseJSONC
}

// Custom parsing with context
{
  parse: (data, languages, namespaces) => {
    const parsed = JSON.parse(data);
    return {
      ...parsed,
      _meta: {
        languages,
        namespaces,
        loadedAt: new Date().toISOString()
      }
    };
  }
}

// Custom payload for missing keys
{
  parsePayload: (namespace, key, fallbackValue) => ({
    namespace,
    key,
    value: fallbackValue || '',
    timestamp: Date.now()
  })
}

// POST request payload
{
  parseLoadPayload: (languages, namespaces) => ({
    languages: languages.join(','),
    namespaces: namespaces.join(','),
    format: 'json'
  })
}

Payload Serialization

Custom function for serializing request payloads before sending.

/**
 * Serialize payload before sending in POST requests
 * @param payload - Object to serialize
 * @returns Serialized string representation
 */
stringify?(payload: any): string;

Default:

JSON.stringify

Usage Examples:

// Custom JSON serializer
{
  stringify: (payload) => JSON.stringify(payload, null, 2)
}

// YAML serialization
{
  stringify: (payload) => yaml.dump(payload)
}

// URL-encoded form data
{
  stringify: (payload) => new URLSearchParams(payload).toString()
}

HTTP Request Configuration

Options for controlling HTTP request behavior.

/**
 * Cross-domain request settings
 */
crossDomain?: boolean;        // Default: false
withCredentials?: boolean;    // Default: false
overrideMimeType?: boolean;   // Default: false (XMLHttpRequest only, forces JSON mime type)

/**
 * URL query parameters added to all requests
 */
queryStringParams?: { [key: string]: string };

/**
 * Custom HTTP headers (static object or function)
 */
customHeaders?: { [key: string]: string } | (() => { [key: string]: string });

/**
 * Fetch API request options (static or function)
 */
requestOptions?: RequestInit | ((payload: {} | string) => RequestInit);

Usage Examples:

// Basic headers and query params
{
  customHeaders: {
    'Authorization': 'Bearer token123',
    'Accept-Language': 'en-US'
  },
  queryStringParams: {
    'version': '2.0',
    'format': 'json'
  },
  overrideMimeType: true  // Forces XMLHttpRequest to treat response as JSON
}

// Dynamic headers
{
  customHeaders: () => ({
    'Authorization': `Bearer ${getCurrentToken()}`,
    'X-Request-ID': generateRequestId()
  })
}

// Custom fetch options
{
  requestOptions: {
    mode: 'cors',
    credentials: 'include',
    cache: 'no-cache'
  }
}

// Dynamic fetch options
{
  requestOptions: (payload) => ({
    method: payload ? 'POST' : 'GET',
    mode: 'cors',
    headers: payload ? { 'Content-Type': 'application/json' } : {}
  })
}

Custom Request Handler

Replace the default request implementation with a custom function.

/**
 * Custom request function that completely replaces default HTTP handling
 * @param options - Complete backend options object
 * @param url - Target URL for request
 * @param payload - Request payload (for POST requests)
 * @param callback - Result callback function
 */
request?(options: HttpBackendOptions, url: string, payload: {} | string, callback: RequestCallback): void;

type RequestCallback = (error: any | undefined | null, response: RequestResponse | undefined | null) => void;

interface RequestResponse {
  status: number;
  data: any;
}

Usage Examples:

// Custom request with axios
{
  request: async (options, url, payload, callback) => {
    try {
      const response = await axios({
        url,
        method: payload ? 'POST' : 'GET',
        data: payload,
        headers: options.customHeaders
      });
      callback(null, {
        status: response.status,
        data: response.data
      });
    } catch (error) {
      callback(error, null);
    }
  }
}

Alternative Fetch Function

Low-level fetch interceptor for mocking or custom fetch behavior.

type FetchFunction = (input: string, init: RequestInit) => Promise<Response> | void;

/**
 * Alternative fetch function for intercepting requests
 * Return undefined/void to fall back to default fetch/XMLHttpRequest
 */
alternateFetch?: FetchFunction;

Auto-reload Configuration

Automatic periodic reloading of translation resources.

/**
 * Automatic reload interval in milliseconds
 * Set to false to disable auto-reload
 */
reloadInterval?: false | number;

Default:

false
(browser),
3600000
(1 hour, Node.js)

Usage Examples:

// Reload every 5 minutes
{
  reloadInterval: 5 * 60 * 1000
}

// Disable auto-reload
{
  reloadInterval: false
}

Default Configuration

The backend uses these defaults when options are not specified:

{
  loadPath: '/locales/{{lng}}/{{ns}}.json',
  addPath: '/locales/add/{{lng}}/{{ns}}',
  parse: JSON.parse,
  stringify: JSON.stringify,
  parsePayload: (namespace, key, fallbackValue) => ({ [key]: fallbackValue || '' }),
  parseLoadPayload: () => undefined,
  reloadInterval: typeof window !== 'undefined' ? false : 60 * 60 * 1000,
  customHeaders: {},
  queryStringParams: {},
  crossDomain: false,
  withCredentials: false,
  overrideMimeType: false,
  requestOptions: {
    mode: 'cors',
    credentials: 'same-origin',
    cache: 'default'
  }
}