Author:
    Creation:2024-08-13Last update:2026-08-30

    Intlayer Configuration Documentation

    Overview

    Intlayer configuration files allow customization of various aspects of the plugin, such as internationalization, middleware, and content handling. This document provides a detailed description of each property in the configuration.

    Table of Contents

    Configuration File Support

    Intlayer accepts JSON, JS, MJS, and TS configuration file formats:

    • intlayer.config.ts
    • intlayer.config.js
    • intlayer.config.json
    • intlayer.config.json5
    • intlayer.config.jsonc
    • intlayer.config.cjs
    • intlayer.config.mjs
    • .intlayerrc

    Example config file

    intlayer.config.ts
    import { Locales, type IntlayerConfig } from "intlayer";
    import { nextjsRewrite } from "intlayer/routing";
    import { syncJSON } from "@intlayer/sync-json-plugin";
    import { z } from "zod";
    
    /**
     * Example Intlayer configuration file showing all available options.
     */
    const config: IntlayerConfig = {
      /**
       * Configuration for internationalization settings.
       */
      internationalization: {
        /**
         * List of supported locales in the application.
         * Default: [Locales.ENGLISH]
         */
        locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],
    
        /**
         * List of required locales that must be defined in every dictionary.
         * If empty, all locales are required in `strict` mode.
         * Default: []
         */
        requiredLocales: [Locales.ENGLISH],
    
        /**
         * Strictness level for internationalized content.
         * - "strict": Errors if any declared locale is missing or undeclared.
         * - "inclusive": Warnings if a declared locale is missing.
         * - "loose": Accepts any existing locale.
         * Default: "inclusive"
         */
        strictMode: "inclusive",
    
        /**
         * Default locale used as a fallback if the requested locale is not found.
         * Default: Locales.ENGLISH
         */
        defaultLocale: Locales.ENGLISH,
      },
    
      /**
       * Settings that control dictionary operations and fallback behavior.
       */
      dictionary: {
        /**
         * Controls how dictionaries are imported.
         * - "static": Statically imported at build time.
         * - "dynamic": Dynamically imported using Suspense.
         * - "fetch": Fetched dynamically via the live sync API.
         * Default: "static"
         */
        importMode: "static",
    
        /**
         * Strategy for auto-filling missing translations using AI.
         * Can be a boolean or a path pattern to store filled content.
         * Default: true
         */
        fill: true,
    
        /**
         * Physical location of the dictionary files.
         * - "local": Stored in the local filesystem.
         * - "remote": Stored in the Intlayer CMS.
         * - "hybrid": Stored in the local filesystem and the Intlayer CMS.
         * - "plugin" (or any custom string): Provided by a plugin or a custom source.
         * Default: "local"
         */
        location: "local",
    
        /**
         * Whether to automatically transform content (e.g., Markdown to HTML).
         * Default: false
         */
        contentAutoTransformation: false,
      },
    
      /**
       * Routing and middleware configuration.
       */
      routing: {
        /**
         * Locale routing strategy.
         * - "prefix-no-default": Prefix all except the default locale (e.g., /dashboard, /fr/dashboard).
         * - "prefix-all": Prefix all locales (e.g., /en/dashboard, /fr/dashboard).
         * - "no-prefix": No locale in the URL.
         * - "search-params": Use ?locale=...
         * Default: "prefix-no-default"
         */
        mode: "prefix-no-default",
    
        /**
         * Enables the Intlayer locale-routing proxy (middleware).
         * Handles locale detection, redirects and rewrites in dev, preview and SSR.
         * - unset (auto): development and preview servers keep locale routing
         *   URL-driven by ignoring the locale stored in cookies and headers.
         *   Prefixes still resolve, the locale is still persisted, and
         *   Accept-Language detection still applies. Production behaves like `true`.
         * - true: full behaviour in every environment.
         * - false: no locale routing.
         * Default: undefined (auto)
         */
        enableProxy: undefined,
    
        /**
         * Where to store the user's selected locale.
         * Options: 'cookie', 'localStorage', 'sessionStorage', 'header', or an array of these.
         * Default: ['cookie', 'header']
         */
        storage: ["cookie", "header"],
    
        /**
         * Base path for the application URLs.
         * Default: ""
         */
        basePath: "",
    
        /**
         * Custom URL rewriting rules for locale-specific paths.
         */
        rewrite: nextjsRewrite({
          "/[locale]/about": {
            en: "/[locale]/about",
            fr: "/[locale]/a-propos",
          },
        }),
    
        /**
         * Maps locales to domain hostnames for domain-based routing.
         * URLs for these locales will be absolute (e.g., https://intlayer.cn/).
         * The domain implies the locale, so no locale prefix is added to the path.
         * Default: undefined
         */
        domains: {
          en: "intlayer.org",
          zh: "intlayer.cn",
        },
      },
    
      /**
       * Settings for finding and processing content files.
       */
      content: {
        /**
         * File extensions to scan for dictionaries.
         * Default: ['.content.ts', '.content.js', '.content.json', etc.]
         */
        fileExtensions: [".content.ts", ".content.js", ".content.json"],
    
        /**
         * Directories where .content files are located.
         * Default: ["."]
         */
        contentDir: ["src"],
    
        /**
         * Directories where source code is located.
         * Used for build optimization and code transformation.
         * Default: ["."]
         */
        codeDir: ["src"],
    
        /**
         * Patterns to exclude from scanning.
         * Default: ['node_modules', '.intlayer', etc.]
         */
        excludedPath: ["node_modules"],
    
        /**
         * Whether to watch for changes and rebuild dictionaries in development.
         * Default: true in development
         */
        watch: true,
    
        /**
         * Command to format newly created <br/> updated .content files.
         */
        formatCommand: 'npx prettier --write "{{file}}"',
      },
    
      /**
       * Visual Editor configuration.
       */
      editor: {
        /**
         * Whether the visual editor is enabled.
         * Default: false
         */
        enabled: true,
    
        /**
         * URL of your application for origin validation.
         * Default: ""
         */
        applicationURL: "http://localhost:3000",
    
        /**
         * Port for the local editor server.
         * Default: 8000
         */
        port: 8000,
    
        /**
         * Public URL for the editor.
         * Default: "http://localhost:8000"
         */
        editorURL: "http://localhost:8000",
    
        /**
         * Intlayer CMS URL.
         * Default: "https://app.intlayer.org"
         */
        cmsURL: "https://app.intlayer.org",
    
        /**
         * Backend API URL.
         * Default: "https://back.intlayer.org"
         */
        backendURL: "https://back.intlayer.org",
    
        /**
         * Whether to enable real-time content synchronization.
         * Default: false
         */
        liveSync: true,
      },
    
      /**
       * Analytics configuration.
       */
      analytics: {
        /**
         * Whether analytics collection is enabled (page views, content exposures, A/B events).
         * Requires `@intlayer/analytics` to be installed, and `editor.clientId` to be set for attribution.
         * Default: true
         */
        enabled: true,
    
        /**
         * Milliseconds between automatic batched flushes to the backend.
         * Default: 20000
         */
        flushInterval: 20000,
    
        /**
         * Fraction of sessions to record, from 0 (none) to 1 (all).
         * Default: 1
         */
        sampleRate: 1,
      },
    
      /**
       * AI-powered translation and generation settings.
       */
      ai: {
        /**
         * AI provider to use.
         * Options: 'openai', 'anthropic', 'mistral', 'deepseek', 'gemini', 'ollama', 'openrouter', 'alibaba', 'fireworks', 'groq', 'huggingface', 'bedrock', 'googlevertex', 'togetherai', 'lmstudio', 'moonshotai'
         * Default: 'openai'
         */
        provider: "openai",
    
        /**
         * Model to use from the selected provider.
         */
        model: "gpt-4o",
    
        /**
         * Provider API key.
         */
        apiKey: process.env.OPENAI_API_KEY,
    
        /**
         * Global context to guide the AI in generating translations.
         */
        applicationContext: "This is a travel booking application.",
    
        /**
         * Base URL for the AI API.
         */
        baseURL: "http://localhost:3000",
    
        /**
         * Data serialization
         *
         * Options:
         * - "json": Standard, reliable; uses more tokens.
         * - "toon": Fewer tokens, less consistent than JSON.
         *
         * Default: "json"
         */
        dataSerialization: "json",
      },
    
      /**
       * Build and optimization settings.
       */
      build: {
        /**
         * Preparation of .intlayer folder before building.
         * By default it try to prepare the intlayer content before the app build, but it can also be triggered manually by running the command `intlayer build`..
         * - "auto": Automatic build during app build.
         * - "manual": Requires explicit build command.
         * Default: "auto"
         */
        mode: "auto",
    
        /**
         * Whether to optimize the final bundle by pruning unused dictionaries.
         * Default: true in production
         */
        optimize: true,
    
        /**
         * Minify the dictionaries to reduce the bundle size.
         * Default: false
         *
         * Note:
         * - This option will be ignored if `optimize` is disabled.
         * - This option will be ignored if `editor.enabled` is true.
         */
        minify: true,
    
        /**
         * Purge the unused keys in a dictionaries.
         * Default: false
         *
         * Note:
         * - This option will be ignored if `optimize` is disabled.
         */
        purge: true,
    
        /**
         * Group the per-locale dictionary chunks by the code-split boundary that uses
         * them, so a lazily loaded page fetches its content in one request.
         * Default: true
         *
         * Note:
         * - Only applies to dictionaries using `importMode: 'dynamic'`.
         */
        chunkGrouping: true,
    
        /**
         * Load a dictionary together with the chunk that uses it, instead of fetching
         * it once that chunk renders. Readers render synchronously instead of
         * suspending, so navigating no longer flashes a loading state.
         * Default: true
         *
         * Note:
         * - Only the resolved locale is awaited, so a page still downloads only the
         *   language it renders.
         */
        dictionariesPreload: true,
    
        /**
         * Output format for generated dictionary files.
         * Default: ['cjs', 'esm']
         */
        outputFormat: ["cjs", "esm"],
    
        /**
         * Indicates if the build should check TypeScript types.
         * Default: false
         */
        checkTypes: false,
      },
    
      /**
       * Logger configuration.
       */
      log: {
        /**
         * Logging level.
         * - "default": Standard logging.
         * - "verbose": Detailed debug logging.
         * - "disabled": No logging.
         * Default: "default"
         */
        mode: "default",
    
        /**
         * Prefix for all log messages.
         * Default: "[intlayer]"
         */
        prefix: "[intlayer]",
      },
    
      /**
       * System configuration (Advanced use cases)
       */
      system: {
        /**
         * Directory for storing localization dictionaries.
         */
        dictionariesDir: ".intlayer/dictionary",
    
        /**
         * Directory for module augmentation.
         */
        moduleAugmentationDir: ".intlayer/types",
    
        /**
         * Directory for storing unmerged dictionaries.
         */
        unmergedDictionariesDir: ".intlayer/unmerged_dictionary",
    
        /**
         * Directory for storing dictionary types.
         */
        typesDir: ".intlayer/types",
    
        /**
         * Directory where main application files are stored.
         */
        mainDir: ".intlayer/main",
    
        /**
         * Directory where the configuration files are stored.
         */
        configDir: ".intlayer/config",
    
        /**
         * Directory where the cache files are stored.
         */
        cacheDir: ".intlayer/cache",
      },
    
      /**
       * Compiler configuration (Advanced use cases)
       */
      compiler: {
        /**
         * Indicates if the compiler should be enabled.
         *
         * - false: Disable the compiler.
         * - true: Enable the compiler.
         * - "build-only": Skip the compiler during development and speed up start times.
         *
         * Default: false
         */
        enabled: true,
    
        /**
         * Defines the output files path. Replaces `outputDir`.
         *
         * - `./` paths are resolved relative to the component directory.
         * - `/` paths are resolved relative to the project root (`baseDir`).
         *
         * - Including the `{{locale}}` variable in the path will trigger the generation of separate dictionaries per locale.
         *
         * Example:
         * ```ts
         * {
         *   // Create Multilingual .content.ts files close to the component
         *   output: ({ fileName, extension }) => `./${fileName}${extension}`,
         *
         *   // output: './{{fileName}}{{extension}}', // Equivalent using template string
         * }
         * ```
         *
         * ```ts
         * {
         *   // Create centralize per-locale JSON at the root of the project
         *   output: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,
         *
         *   // output: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string
         * }
         * ```
         *
         * Variable list:
         *   - `fileName`: The name of the file.
         *   - `key`: The key of the content.
         *   - `locale`: The locale of the content.
         *   - `extension`: The extension of the file.
         *   - `componentFileName`: The name of the component file.
         *   - `componentExtension`: The extension of the component file.
         *   - `format`: The format of the dictionary.
         *   - `componentFormat`: The format of the component dictionary.
         *   - `componentDirPath`: The directory path of the component.
         */
        output: ({ locale, key }) => `compiler/${locale}/${key}.json`,
    
        /**
         * Indicates if the components should be saved after being transformed.
         *
         * - If `true`, the compiler will rewrite the component file in the disk. So the transformation will be permanent, and the compiler will skip the transformation for the next process. That way, the compiler can transform the app, and then it can be removed.
         *
         * - If `false`, the compiler will inject the `useIntlayer()` function call into the code in the build output only, and keep the base codebase intact. The transformation will be done only in memory.
         */
        saveComponents: false,
    
        /**
         * Inset only content into the generated file. Useful for per-locale i18next or ICU MessageFormat JSON outputs.
         */
        noMetadata: false,
    
        /**
         * Dictionary key prefix
         */
        dictionaryKeyPrefix: "", // Add an optional prefix for the extracted dictionary keys
      },
    
      /**
       * Custom schemas to validate the dictionaries content.
       */
      schemas: {
        "my-schema": z.object({
          title: z.string(),
        }),
      },
    
      /**
       * Dictionary configuration.
       */
      dictionary: {
        /**
         * Controls how dictionaries are imported.
         * - "static": Statically imported at build time.
         * - "dynamic": Dynamically imported using Suspense.
         * - "fetch": Fetched dynamically via the live sync API.
         */
        importMode: "static",
    
        /**
         * The default message format for all dictionaries in the project.
         * - 'intlayer': Native intlayer format (default).
         * - 'icu': ICU message format (used by next-intl, react-intl, etc.).
         * - 'i18next': i18next interpolation format (used by i18next, react-i18next, next-i18next).
         * - 'vue-i18n': Vue I18n format (used by vue-i18n).
         * - 'po': GNU Gettext PO format.
         */
        format: "icu",
      },
    
      /**
       * Plugins configuration.
       */
      plugins: [
        syncJSON({
          format: "icu",
          source: ({ locale }) => `./messages/${locale}.json`,
        }),
      ],
    };
    
    export default config;
    

    Configuration Reference

    The following sections describe the various configuration settings available for Intlayer.

    Internationalization Configuration

    Defines settings related to internationalization, including available locales and the default locale for the application.

    FieldDescriptionTypeDefaultExampleNote
    localesThe list of supported locales in the application.string[][Locales.ENGLISH]['en', 'fr', 'es']
    requiredLocalesThe list of required locales in the application.string[][][]• If empty, all locales are required in strict mode.
    • Ensure required locales are also defined in the locales field.
    strictModeEnsure strong implementations of internationalized content using TypeScript.string'inclusive'• If "strict": the t function requires each declared locale to be defined - throws an error if one is missing or undeclared.
    • If "inclusive": warns on missing locales but accepts undeclared ones that exist.
    • If "loose": accepts any existing locale.
    defaultLocaleThe default locale used as a fallback if the requested locale is not found.stringLocales.ENGLISH'en'Used to determine the locale when none is specified in the URL, cookie, or header.

    Editor Configuration

    Defines settings related to the integrated editor, including server port and active status.

    FieldDescriptionTypeDefaultExampleNote
    applicationURLThe URL of the application.stringundefined'http://localhost:3000'
    'https://example.com'
    process.env.INTLAYER_EDITOR_URL
    • Used to restrict the origin of the editor for security reasons.
    • If set to '*', the editor is accessible from any origin.
    portThe port used by the visual editor server.number8000
    editorURLThe URL of the editor server.string'http://localhost:8000''http://localhost:3000'
    'https://example.com'
    process.env.INTLAYER_EDITOR_URL
    • Used to restrict the origins that can interact with the application.
    • If set to '*', accessible from any origin.
    • Should be set if port is changed or editor is hosted on a different domain.
    cmsURLThe URL of the Intlayer CMS.string'https://app.intlayer.org''https://app.intlayer.org'
    backendURLThe URL of the backend server.stringhttps://back.intlayer.orghttp://localhost:4000
    enabledIndicates if the application interacts with the visual editor.booleanfalseprocess.env.NODE_ENV !== 'production'• If false, the editor cannot interact with the application.
    • Disabling for specific environments enforces security.
    clientIdAllows intlayer packages to authenticate with the backend using oAuth2. To get an access token, go to intlayer.org/project.string |
    undefined
    undefinedKeep secret; store in environment variables.
    clientSecretAllows intlayer packages to authenticate with the backend using oAuth2. To get an access token, go to intlayer.org/project.string |
    undefined
    undefinedKeep secret; store in environment variables.
    dictionaryPriorityStrategyStrategy to prioritize dictionaries when both local and distant are present.string'local_first''distant_first''distant_first': prioritizes distant over local.
    'local_first': prioritizes local over distant.
    liveSyncIndicates if the app server should hot reload content when a change is detected on the CMS
    Visual Editor
    Backend.
    booleantruetrue• When a dictionary is added/updated, the app updates page content.
    • Live sync externalizes content to another server, which may slightly impact performance.
    • Recommend hosting both on the same machine.
    liveSyncPortThe port of the live sync server.number40004000
    liveSyncURLThe URL of the live sync server.string'http://localhost:{liveSyncPort}''https://example.com'Points to localhost by default; can be changed for a remote live sync server.

    Analytics Configuration

    Defines settings related to Intlayer analytics: collecting which content is actually shown to users (page views, content exposures) and powering content A/B testing.

    Analytics is opt-out: it is enabled by default, and starts collecting as soon as the @intlayer/analytics package is installed and a project key (editor.clientId) is configured for attribution. Set analytics.enabled to false — or leave the package uninstalled — and the whole analytics integration is dead-code-eliminated from your application bundle.

    FieldDescriptionTypeDefaultExampleNote
    enabledEnables analytics collection (page views, content exposures, A/B events).booleantruefalseRequires @intlayer/analytics to be installed and editor.clientId to be set for attribution; otherwise analytics stays disabled even if enabled is true.
    flushIntervalMilliseconds between automatic batched flushes to the backend.number2000010000
    sampleRateFraction of sessions to record, from 0 (none) to 1 (all).number10.5Sampling is deterministic per session, so a recorded session reports all of its events (no partial funnels).

    Routing Configuration

    Settings that control routing behavior, including URL structure, locale storage, and middleware handling.

    FieldDescriptionTypeDefaultExampleNote
    modeURL routing mode for locale handling.'prefix-no-default' |
    'prefix-all' |
    'no-prefix' |
    'search-params'
    'prefix-no-default''prefix-no-default': /dashboard (en) or /fr/dashboard (fr). 'prefix-all': /en/dashboard. 'no-prefix': locale handled via other means. 'search-params': /dashboard?locale=frDoes not impact cookie or locale storage management.
    enableProxyEnables the Intlayer locale-routing proxy (middleware).boolean |
    undefined
    undefined (auto)true• Unset (auto): development and preview servers ignore the locale stored in cookies/headers as a redirect source; prefixes, persistence and Accept-Language detection still apply. Production behaves like true.
    true: full behaviour everywhere.
    false: no locale routing. On Next.js, the intlayerProxy middleware becomes a pass-through.
    storageConfiguration for storing the locale in the client.false |
    'cookie' |
    'localStorage' |
    'sessionStorage' |
    'header' |
    CookiesAttributes |
    StorageAttributes |
    Array
    ['cookie', 'header']'localStorage'
    [{ type: 'cookie', name: 'custom-locale', secure: true }]
    See Storage Options table below.
    basePathThe base path for the application URLs.string'''/my-app'If app is at https://example.com/my-app, basePath is '/my-app'and URLs becomehttps://example.com/my-app/en`.
    rewriteCustom URL rewriting rules that override the default routing mode for specific paths. Supports [param] dynamic parameters.Record<string, StrictModeLocaleMap<string>>undefinedSee example below• Rewrite rules take precedence over mode.
    • Works with Next.js and Vite.
    getLocalizedUrl() automatically applies matching rules.
    • See Custom URL Rewrites.
    domainsMaps locales to domain hostnames for domain-based routing. When set, URLs for that locale use this domain as a base (absolute URL) and no locale prefix is added to the path.Partial<Record<Locale, string>>undefined{ zh: 'intlayer.zh', fr: 'intlayer.org' }• Default protocol is https:// if not included in the hostname.
    • The domain itself identifies the locale, so no /zh/ prefix is added.
    getLocalizedUrl('/', 'zh') returns https://intlayer.zh/.

    rewrite example:

    typescript
    routing: {
      mode: "prefix-no-default", // Fallback strategy
      rewrite: nextjsRewrite({
        "/about": {
          en: "/about",
          fr: "/a-propos",
        },
        "/product/[slug]": {
          en: "/product/[slug]",
          fr: "/produit/[slug]",
        },
        "/blog/[category]/[id]": {
          en: "/blog/[category]/[id]",
          fr: "/journal/[category]/[id]",
        },
      }),
    }
    

    Storage Options

    ValueNoteDescription
    'cookie'• For GDPR compliance, ensure proper user consent.
    • Customizable via CookiesAttributes ({ type: 'cookie', name: 'custom-locale', secure: true, httpOnly: false }).
    Stores locale in cookies - accessible on both client and server side.
    'localStorage'• No expiration unless explicitly cleared.
    • Intlayer proxy cannot access it.
    • Customizable via StorageAttributes ({ type: 'localStorage', name: 'custom-locale' }).
    Stores locale in the browser without expiration - client side only.
    'sessionStorage'• Cleared when tab/window is closed.
    • Intlayer proxy cannot access it.
    • Customizable via StorageAttributes ({ type: 'sessionStorage', name: 'custom-locale' }).
    Stores locale for the duration of the page session - client side only.
    'header'• Useful for API calls.
    • Client side cannot access it.
    • Customizable via StorageAttributes ({ type: 'header', name: 'custom-locale' }).
    Stores or transmits locale via HTTP headers - server side only.

    When using cookie storage, you can configure additional cookie attributes:

    FieldDescriptionType
    nameCookie name. Default: 'INTLAYER_LOCALE'string
    domainCookie domain. Default: undefinedstring
    pathCookie path. Default: undefinedstring
    secureRequire HTTPS. Default: undefinedboolean
    httpOnlyHTTP-only flag. Default: undefinedboolean
    sameSiteSameSite policy.'strict' |
    'lax' |
    'none'
    expiresA number is days from creation; a Date (or ISO date string) is an absolute expiry. Default: undefinedDate |
    number |
    string
    maxAgeLifetime in seconds from creation. Takes precedence over expires. Default: undefinednumber

    Locale Storage Attributes

    When using localStorage or sessionStorage:

    FieldDescriptionType
    typeStorage type.'localStorage' |
    'sessionStorage'
    nameStorage key name. Default: 'INTLAYER_LOCALE'string

    Configuration Examples

    Here are some common configuration examples for the new v7 routing structure:

    Basic Configuration (Default):

    typescript
    import { Locales, type IntlayerConfig } from "intlayer";
    // intlayer.config.ts
    const config: IntlayerConfig = {
      internationalization: {
        locales: ["en", "fr", "es"],
        defaultLocale: "en",
      },
      routing: {
        mode: "prefix-no-default",
        storage: "localStorage",
        basePath: "",
      },
    };
    
    export default config;
    

    GDPR Compliant Configuration:

    typescript
    import { Locales, type IntlayerConfig } from "intlayer";
    // intlayer.config.ts
    const config: IntlayerConfig = {
      internationalization: {
        locales: ["en", "fr", "es"],
        defaultLocale: "en",
      },
      routing: {
        mode: "prefix-no-default",
        storage: [
          {
            type: "localStorage",
            name: "user-locale",
          },
          {
            type: "cookie",
            name: "user-locale",
            secure: true,
            sameSite: "strict",
            httpOnly: false,
          },
        ],
        basePath: "",
      },
    };
    
    export default config;
    

    Search Parameters Mode:

    typescript
    import { Locales, type IntlayerConfig } from "intlayer";
    // intlayer.config.ts
    const config: IntlayerConfig = {
      internationalization: {
        locales: ["en", "fr", "es"],
        defaultLocale: "en",
      },
      routing: {
        mode: "search-params",
        storage: "localStorage",
        basePath: "",
      },
    };
    
    export default config;
    

    No Prefix Mode with Custom Storage:

    typescript
    import { Locales, type IntlayerConfig } from "intlayer";
    // intlayer.config.ts
    const config: IntlayerConfig = {
      internationalization: {
        locales: ["en", "fr", "es"],
        defaultLocale: "en",
      },
      routing: {
        mode: "no-prefix",
        storage: {
          type: "sessionStorage",
          name: "app-locale",
        },
        basePath: "/my-app",
      },
    };
    
    export default config;
    

    Custom URL Rewriting with Dynamic Routes:

    typescript
    // intlayer.config.ts
    import { nextjsRewrite } from "intlayer/routing";
    
    const config: IntlayerConfig = {
      internationalization: {
        locales: ["en", "fr"],
        defaultLocale: "en",
      },
      routing: {
        mode: "prefix-no-default", // Fallback for non-rewritten paths
        storage: "cookie",
        rewrite: nextjsRewrite({
          "/about": {
            en: "/about",
            fr: "/a-propos",
          },
          "/product/[slug]": {
            en: "/product/[slug]",
            fr: "/produit/[slug]",
          },
          "/blog/[category]/[id]": {
            en: "/blog/[category]/[id]",
            fr: "/journal/[category]/[id]",
          },
        }),
      },
    };
    
    export default config;
    

    Content Configuration

    Settings related to content handling within the application, including directory names, file extensions, and derived configurations.

    FieldDescriptionTypeDefaultExampleNote
    watchIndicates if Intlayer should watch for changes in content declaration files to rebuild dictionaries.booleantrue
    fileExtensionsFile extensions to look for when building dictionaries.string[]['.content.ts', '.content.js', '.content.cjs', '.content.mjs', '.content.json', '.content.json5', '.content.jsonc', '.content.tsx', '.content.jsx']['.data.ts', '.data.js', '.data.json']Customizing can help avoid conflicts.
    contentDirDirectory path where content definition files (.content.*) are stored.string[]['.']['src', '../../ui-library', require.resolve("@my-package/content"), '@my-package/content']Used to watch for content files to rebuild dictionaries.
    codeDirDirectory path where the code is stored, relative to the base directory.string[]['.']['src', '../../ui-library']• Used to watch for code files to transform (prune, optimize).
    • Keeping separate from contentDir can improve build performance.
    excludedPathDirectories excluded from content search.string[]['**/node_modules/**', '**/dist/**', '**/build/**', '**/.intlayer/**', '**/.next/**', '**/.nuxt/**', '**/.expo/**', '**/.vercel/**', '**/.turbo/**', '**/.tanstack/**']Not yet used; planned for future implementation.
    formatCommandCommand to format content files when Intlayer writes them locally.stringundefined'npx prettier --write "{{file}}" --log-level silent' (Prettier), 'npx biome format "{{file}}" --write --log-level none' (Biome), 'npx eslint --fix "{{file}}" --quiet' (ESLint){{file}} is replaced with the file path.
    • If not set, Intlayer auto-detects (tries prettier, biome, eslint).

    System Configuration

    Settings related to internal paths and output results of Intlayer. These settings are typically internal and should not need to be modified by the user.

    FieldDescriptionTypeDefaultExampleNote
    baseDirThe base directory for the project.stringprocess.cwd()'/path/to/project'Used to resolve all Intlayer-related directories.
    dictionariesDirThe directory path for storing localization dictionaries.string'.intlayer/dictionary'
    moduleAugmentationDirDirectory for module augmentation, allowing better IDE suggestions and type checking.string'.intlayer/types''intlayer-types'Be sure to include this in tsconfig.json.
    unmergedDictionariesDirThe directory for storing unmerged dictionaries.string'.intlayer/unmerged_dictionary'
    typesDirThe directory for storing dictionary types.string'.intlayer/types'
    mainDirThe directory where main application files are stored.string'.intlayer/main'
    configDirThe directory where configuration files are stored.string'.intlayer/config'
    cacheDirThe directory where cache files are stored.string'.intlayer/cache'

    Dictionary Configuration

    Settings that control dictionary operations, including auto-fill behavior and content generation.

    This dictionary configuration serves two main purposes:

    1. Default Values: Define default values when creating content declaration files
    2. Fallback Behavior: Provide fallback values when specific fields are not defined, allowing you to define dictionary operation behavior globally

    For more information about content declaration files and how configuration values are applied, see the Content File Documentation.

    FieldDescriptionTypeDefaultExampleNote
    fillControls how auto-fill (AI translation) output files are generated.boolean |
    FilePathPattern |
    Partial<Record<Locale, boolean | FilePathPattern>>
    true{ en: '/locales/en/{{key}}.json', fr: ({ key }) => '/locales/fr/${key}.json', es: false }true: default path (same file as source).
    false: disable.
    • String/function template generates per-locale files.
    • Object per-locale: each locale maps to its own pattern; false skips that locale.
    • Including {{locale}} triggers per-locale generation.
    • Dictionary-level fill always takes priority over this global config.
    descriptionHelps understand the purpose of the dictionary in the editor and CMS. Also used as context for AI translation generation.stringundefined'User profile section'
    localeTransforms the dictionary into a per-locale format. Each field declared becomes a translation node. If absent, the dictionary is treated as multilingual.LocalesValuesundefined'en'Use this when the dictionary is specific to a single locale rather than containing translations for multiple locales.
    contentAutoTransformationAutomatically transforms content strings into typed nodes (markdown, HTML, or insertion).boolean |
    { markdown?: boolean; html?: boolean; insertion?: boolean }
    falsetrue• Markdown: ### Titlemd('### Title').
    • HTML: <div>Title</div>html('<div>Title</div>').
    • Insertion: Hello {{name}}insert('Hello {{name}}').
    locationIndicates where dictionary files are stored and their CMS synchronization mode.'local' |
    'remote' |
    'hybrid' |
    'plugin' |
    string
    'local''hybrid''local': managed locally only.
    'remote': managed remotely only (CMS).
    'hybrid': managed both locally and remotely.
    'plugin' or custom string: managed by a plugin or custom source.
    importModeControls how dictionaries are imported.'static' |
    'dynamic' |
    'fetch'
    'static''dynamic''static': imported statically (replaces useIntlayer with useDictionary).
    'dynamic': imported dynamically via Suspense (replaces with useDictionaryDynamic).
    'fetch': fetched via live sync API; falls back to 'dynamic' on failure.
    • Relies on @intlayer/babel and @intlayer/swc plugins.
    • Keys must be declared statically.
    • Ignored if optimize is disabled.
    • Does not affect getIntlayer, getDictionary, useDictionary, etc.
    formatThe default message format for all dictionaries in the project.'intlayer' |
    'icu' |
    'i18next' |
    'vue-i18n' |
    'po'
    'intlayer''icu''intlayer': Native intlayer format.
    'icu': ICU message format.
    'i18next': i18next interpolation format.
    'vue-i18n': Vue I18n format.
    'po': GNU Gettext PO format.
    priorityPriority of the dictionary. Higher values take precedence over lower ones when resolving conflicts between dictionaries.numberundefined1
    liveDeprecated - use importMode: 'fetch' instead. Indicated whether dictionary content was fetched dynamically via the live sync API.booleanundefinedRenamed to importMode: 'fetch' in v8.0.0.
    schemaAuto-generated by Intlayer for JSON schema validation.'https://intlayer.org/schema.json'auto-generatedDo not modify manually.
    titleHelps identify the dictionary in the editor and CMS.stringundefined'User Profile'
    tagsCategorizes dictionaries and provides context or instructions for the editor and AI.string[]undefined['user', 'profile']
    versionVersion of the remote dictionary; helps track which version is currently in use.stringundefined'1.0.0'• Manageable on the CMS.
    • Do not modify locally.

    fill example:

    ts
    dictionary: {
      fill: {
        en: '/locales/en/{{key}}.content.json',
        fr: ({ key }) => `/locales/fr/${key}.content.json`,
        es: false,
      }
    }
    

    Logger Configuration

    Settings that control the logger, including the prefix to use.

    FieldDescriptionTypeDefaultExampleNote
    modeIndicates the mode of the logger.'default' |
    'verbose' |
    'disabled'
    'default''verbose''verbose': logs more info for debugging.
    'disabled': disables the logger entirely.
    prefixThe prefix of the logger.string'[intlayer] ''[my custom prefix] '

    AI Configuration

    Settings that control the AI features of Intlayer, including the provider, model, and API key.

    This configuration is optional if you're registered on the Intlayer Dashboard using an access key. Intlayer will automatically manage the most efficient and cost-effective AI solution for your needs. Using the default options ensures better long-term maintainability as Intlayer continuously updates to use the most relevant models.

    If you prefer to use your own API key or specific model, you can define your custom AI configuration. This AI configuration will be used globally across your Intlayer environment. CLI commands will use these settings as defaults for the commands (e.g. fill), as well as the SDK, Visual Editor, and CMS. You can override these default values for specific use cases using command parameters.

    Intlayer supports multiple AI providers for enhanced flexibility and choice. Currently supported providers are:

    • OpenAI (default)
    • Anthropic Claude
    • Mistral AI
    • DeepSeek
    • Google Gemini
    • Google AI Studio
    • Google Vertex
    • Meta Llama
    • Ollama
    • OpenRouter
    • Alibaba Cloud
    • Fireworks
    • Hugging Face
    • Groq
    • Amazon Bedrock
    • Together.ai
    • LM Studio
    • ollama
    FieldDescriptionTypeDefaultExampleNote
    providerThe provider to use for the AI features of Intlayer.'openai' |
    'anthropic' |
    'mistral' |
    'deepseek' |
    'gemini' |
    'ollama' |
    'openrouter' |
    'alibaba' |
    'fireworks' |
    'groq' |
    'huggingface' |
    'bedrock' |
    'googleaistudio' |
    'googlevertex' |
    'togetherai' |
    'lmstudio' |
    'moonshotai'
    undefined'anthropic'Different providers require different API keys and have different pricing.
    modelThe model to use for AI features.stringNone'gpt-4o-2024-11-20'Specific model varies by provider.
    temperatureControls the randomness of AI responses.numberNone0.1Higher temperature = more creative and less predictable.
    apiKeyYour API key for the selected provider.stringNoneprocess.env.OPENAI_API_KEYKeep secret; store in environment variables.
    applicationContextAdditional context about your application to help the AI generate more accurate translations (domain, audience, tone, terminology).stringNone'My application context'Can be used to add rules (e.g. "You should not transform urls").
    baseURLThe base URL for the AI API.stringNone'https://api.openai.com/v1'
    'http://localhost:5000'
    Can point to a local or custom AI API endpoint.
    dataSerializationData serialization format for AI features.'json' |
    'toon'
    undefined'toon''json': standard, reliable; uses more tokens.
    'toon': fewer tokens, less consistent.
    • Additional parameters are passed to the AI model as context (reasoning effort, verbosity, etc.).

    Build Configuration

    Settings that control how Intlayer optimizes and builds your application's internationalization.

    Build options apply to the @intlayer/babel and @intlayer/swc plugins.

    In development mode, Intlayer uses static imports for dictionaries to simplify the development experience.
    When optimized, Intlayer will replace dictionary calls to optimize chunking, so the final bundle only imports dictionaries that are actually used.
    FieldDescriptionTypeDefaultExampleNote
    modeControls the mode of the build.'auto' |
    'manual'
    'auto''manual''auto': build enabled automatically when the application is built.
    'manual': only runs when the build command is executed.
    • Can be used to disable dictionary builds (e.g. to avoid running in Node.js environments).
    optimizeControls whether the build should be optimized.booleanundefinedprocess.env.NODE_ENV === 'production'• If unset, optimization is triggered on framework build (Vite/Next.js).
    true forces optimization including dev mode.
    false disables it.
    • When enabled, replaces dictionary calls to optimize chunking - only used dictionaries are imported.
    • Relies on @intlayer/babel and @intlayer/swc plugins.
    • Keys must be declared statically.
    minifyDefines if the dictionaries should be minified to reduce the bundle size.booleanfalse• Defines if the bundle should be minified.
    • Default: false in production.
    • This option will be ignored if optimize is disabled.
    • This option will be ignored if editor.enabled is true.
    pruneDefines if the unused keys in dictionaries should be purged.booleantrue• Defines if the bundle should be pruned.
    • Default: true in production.
    • This option will be ignored if optimize is disabled.
    checkTypesIndicates if the build should check TypeScript types and log errors.booleanfalseCan slow down the build.
    chunkGroupingWhether to group the per-locale dictionary chunks by the code-split boundary that uses them.booleantrue• Without grouping, a page assembled from many components issues one request per dictionary.
    • Dictionaries reached from several boundaries move to a shared chunk, so no page ships another page's content.
    • Only applies to dictionaries using importMode: 'dynamic'.
    • Only applies to the client build, and only when bundling (not in dev).
    dictionariesPreloadWhether a dictionary should load together with the chunk that uses it, instead of being fetched once that chunk renders.booleantrue• The generated entry point awaits the browsing locale at the top level, so a lazily loaded route is not considered loaded until its content is there.
    • Readers render synchronously instead of suspending, so navigating no longer flashes a loading state.
    • Only the resolved locale is awaited, so a page still downloads only the language it renders.
    • Only applies to dictionaries using importMode: 'dynamic', on the client build.
    • Requires a bundler supporting top-level await (Vite, esbuild).
    outputFormatControls the output format of the dictionaries.('esm' | 'cjs')[]['esm', 'cjs']['cjs']
    traversePatternPatterns defining which files to traverse during optimization.string[]['**/*.{tsx,ts,js,mjs,cjs,jsx,vue,svelte,svte}', '!**/node_modules/**', '!**/dist/**', '!**/.intlayer/**', '!**/*.config.*', '!**/*.test.*', '!**/*.spec.*', '!**/*.stories.*']['src/**/*.{ts,tsx}', '../ui-library/**/*.{ts,tsx}', '!**/node_modules/**']• Limit optimization to relevant files to improve build performance.
    • Ignored if optimize is disabled.
    • Uses glob pattern.

    Compiler Configuration

    Settings that control the Intlayer compiler, which extracts dictionaries straight from your components.

    FieldDescriptionTypeDefaultExampleNote
    enabledIndicates if the compiler should be enabled to extract dictionaries.boolean |
    'build-only'
    true'build-only''build-only' skips the compiler during development to speed up builds; only runs on build commands.
    dictionaryKeyPrefixPrefix for the extracted dictionary keys.string'''my-key-'Added to the generated key (based on file name) to prevent conflicts.
    saveComponentsIndicates if components should be saved after being transformed.booleanfalse• If true, replaces original files with transformed files.
    • The compiler can then be removed after one run.
    outputDefines the output file path. Replaces outputDir. Supports template variables: {{fileName}},
    {{key}},
    {{locale}},
    {{extension}},
    {{componentFileName}},
    {{componentExtension}},
    {{format}},
    {{componentFormat}},
    {{componentDirPath}}.
    boolean |
    FilePathPattern |
    Partial<Record<Locale, boolean | FilePathPattern>>
    undefined'./{{fileName}}{{extension}}'
    '/locales/{{locale}}/{{key}}.json'
    { en: ({ key }) => './locales/en/${key}.json', fr: '...', es: false }
    ./ paths resolve relative to the component directory.
    / paths resolve relative to the project root.
    • Including {{locale}} generates separate per-locale dictionaries.
    • Supports per-locale object notation; false skips that locale.
    noMetadataIf true, the compiler omits dictionary metadata (key, content wrapper) from the output.booleanfalsefalse{"key":"my-key","content":{"key":"value"}}
    true{"key":"value"}
    • Useful for i18next or ICU MessageFormat JSON outputs.
    • Works well with loadJSON plugin.
    dictionaryKeyPrefixDictionary key prefixstring''Add an optional prefix for the extracted dictionary keys

    Custom Schemas

    FieldDescriptionType
    schemasPermet de définir des schémas Zod pour valider la structure de vos dictionnaires.Record<string, ZodSchema>

    Plugins

    FieldDescriptionType
    pluginsListe des plugins Intlayer à activer.IntlayerPlugin[]

    Frequently Asked Questions

    At the root of your project, next to package.json. Intlayer also accepts intlayer.config.js, intlayer.config.mjs, intlayer.config.cjs and JSON, so the file matches whichever module system your project uses.

    Much less than a namespace based setup, because a page never downloads a catalogue it does not render. Server rendered markup resolves its content on the server, and the build time compiler replaces useIntlayer calls with the exact dictionary entries a component uses, so unused keys and unused languages are dropped. Dynamic dictionaries split the rest per locale. Measured against the usual alternatives, Intlayer reduces bundle and page size by up to 50%. See bundle optimization and the benchmark.

    Yes, and there are two paths. You can migrate the content progressively with the i18next migration guide or the next-intl migration guide. Or you can keep your current API entirely: the compat adapters expose the exact same API as i18next, react-i18next, next-intl, next-i18next, react-intl, use-intl, vue-i18n and Lingui, but served by Intlayer dictionaries, so imports change and component code does not.

    Yes. The sync JSON plugin keeps your /messages/{locale}/{namespace}.json files as the source of truth and generates Intlayer dictionaries from them, in both directions. A sync PO plugin does the same for gettext catalogues, and per locale files let you split content by language instead of grouping locales in one file.

    No. Run npx intlayer extract and Intlayer reads your source files, pulls the user facing strings out and writes a .content file next to each one, so you review a diff instead of copying strings into a catalogue one at a time. See the extract command.

    For a fully automated pipeline, the Intlayer Compiler does the same at build time on JSX, TSX, Vue and Svelte source, generating the dictionaries on every change so there are no keys to maintain by hand. It works by static analysis, so strings that only exist at runtime stay out of reach, and it needs a few annotations to tell user facing text apart from application logic.

    Five pieces, all optional:

    • VS Code extension: jump from a useIntlayer key to the content file that declares it, extract content from a component, and run build, fill, test, push and pull from the command palette or a dedicated Intlayer tab.
    • LSP server: the same awareness in any editor that speaks LSP, with go to definition, find all references, hover previews of a translated value, autocompletion of keys and fields, and a warning when a key is not declared anywhere. It also resolves i18next, react-i18next, next-intl and use-intl calls, which helps while you migrate.
    • MCP server: exposes the Intlayer documentation and CLI to Cursor, VS Code, Claude Desktop, Claude Code and ChatGPT, so an assistant answers from current docs instead of guessing, and can run commands such as intlayer fill itself.
    • Agent skills: focused skills such as intlayer-config, intlayer-cli and intlayer-content, plus one per framework, that teach an agent your routing setup and the content node types.
    • ESLint plugin: no-raw-text flags hardcoded strings, with further rules for static dictionary keys and unused content.