Author:
    Creation:2025-12-30Last update:2026-08-29

    Translate your Fastify backend website using Intlayer | Internationalization (i18n)

    fastify-intlayer is a powerful internationalization (i18n) plugin for Fastify applications, designed to make your backend services globally accessible by providing localized responses based on the client's preferences.

    See package implementation on GitHub: https://github.com/aymericzip/intlayer/tree/main/packages/fastify-intlayer

    Practical Use Cases

    • Displaying Backend Errors in User's Language: When an error occurs, displaying messages in the user's native language improves understanding and reduces frustration. This is especially useful for dynamic error messages that might be shown in front-end components like toasts or modals.
    • Retrieving Multilingual Content: For applications pulling content from a database, internationalization ensures that you can serve this content in multiple languages. This is crucial for platforms like e-commerce sites or content management systems that need to display product descriptions, articles, and other content in the language preferred by the user.
    • Sending Multilingual Emails: Whether it's transactional emails, marketing campaigns, or notifications, sending emails in the recipient’s language can significantly increase engagement and effectiveness.
    • Multilingual Push Notifications: For mobile applications, sending push notifications in a user's preferred language can enhance interaction and retention. This personal touch can make notifications feel more relevant and actionable.
    • Other Communications: Any form of communication from the backend, such as SMS messages, system alerts, or user interface updates, benefits from being in the user's language, ensuring clarity and enhancing the overall user experience.

    By internationalizing the backend, your application not only respects cultural differences but also aligns better with global market needs, making it a key step in scaling your services worldwide.

    Getting Started

    ide.intlayer.org

    See Application Template on GitHub.

    Installation

    To begin using fastify-intlayer, install the package using npm:

    bash
    npx intlayer init --interactive
    
    the --interactive flag is optional. Use intlayer-cli init if you're an AI agent.
    This command will detect your environment and install the required packages. For example:
    bash
    npm install intlayer fastify-intlayer
    

    Setup

    Configure the internationalization settings by creating an intlayer.config.ts in your project root:

    intlayer.config.ts
    import { Locales, type IntlayerConfig } from "intlayer";
    
    const config: IntlayerConfig = {
      internationalization: {
        locales: [
          Locales.ENGLISH,
          Locales.FRENCH,
          Locales.SPANISH_MEXICO,
          Locales.SPANISH_SPAIN,
        ],
        defaultLocale: Locales.ENGLISH,
      },
    };
    
    export default config;
    

    Declare Your Content

    Create and manage your content declarations to store translations:

    src/index.content.ts
    import { t, type Dictionary } from "intlayer";
    
    const indexContent = {
      key: "index",
      content: {
        exampleOfContent: t({
          en: "Example of returned content in English",
          fr: "Exemple de contenu renvoyé en français",
          "es-ES": "Ejemplo de contenido devuelto en español (España)",
          "es-MX": "Ejemplo de contenido devuelto en español (México)",
        }),
      },
    } satisfies Dictionary;
    
    export default indexContent;
    
    Your content declarations can be defined anywhere in your application as soon as they are included into the contentDir directory (by default, ./src). And match the content declaration file extension (by default, .content.{json,ts,tsx,js,jsx,mjs,cjs,md,mdx,yaml,yml}).
    For more details, refer to the content declaration documentation.

    Fastify Application Setup

    Setup your Fastify application to use fastify-intlayer:

    src/index.ts
    import Fastify from "fastify";
    import { intlayer, t, getDictionary, getIntlayer } from "fastify-intlayer";
    import dictionaryExample from "./index.content";
    
    const fastify = Fastify({ logger: true });
    
    // Load internationalization plugin
    await fastify.register(intlayer);
    
    // Routes
    fastify.get("/t_example", async (_req, reply) => {
      return t({
        en: "Example of returned content in English",
        fr: "Exemple de contenu renvoyé en français",
        "es-ES": "Ejemplo de contenido devuelto en español (España)",
        "es-MX": "Ejemplo de contenido devuelto en español (México)",
      });
    });
    
    fastify.get("/getIntlayer_example", async (_req, reply) => {
      return getIntlayer("index").exampleOfContent;
    });
    
    fastify.get("/getDictionary_example", async (_req, reply) => {
      return getDictionary(dictionaryExample).exampleOfContent;
    });
    
    // Start server
    const start = async () => {
      try {
        await fastify.listen({ port: 3000 });
      } catch (err) {
        fastify.log.error(err);
        process.exit(1);
      }
    };
    
    start();
    

    Compatibility

    fastify-intlayer is fully compatible with:

    It also works seamlessly with any internationalization solution across various environments, including browsers and API requests. You can customize the middleware to detect locale through headers or cookies:

    intlayer.config.ts
    import { Locales, type IntlayerConfig } from "intlayer";
    
    const config: IntlayerConfig = {
      // ... Other configuration options
      routing: {
        storage: [
          { type: "header", name: "my-locale-header" },
          { type: "cookie", name: "my-locale-cookie" },
        ],
      },
    };
    
    export default config;
    

    By default, fastify-intlayer will interpret the Accept-Language header to determine the client's preferred language.

    For more information on configuration and advanced topics, visit our documentation.

    Configure TypeScript

    fastify-intlayer leverages the robust capabilities of TypeScript to enhance the internationalization process. TypeScript's static typing ensures that every translation key is accounted for, reducing the risk of missing translations and improving maintainability.

    Ensure the autogenerated types (by default at ./types/intlayer.d.ts) are included in your tsconfig.json file.

    tsconfig.json
    {
      // ... Your existing TypeScript configurations
      "include": [
        // ... Your existing TypeScript configurations
        ".intlayer/**/*.ts", // Include the auto-generated types
      ],
    }
    

    VS Code Extension

    To improve your development experience with Intlayer, you can install the official Intlayer VS Code Extension.

    Install from the VS Code Marketplace

    This extension provides:

    • Autocompletion for translation keys.
    • Real-time error detection for missing translations.
    • Inline previews of translated content.
    • Quick actions to easily create and update translations.

    For more details on how to use the extension, refer to the Intlayer VS Code Extension documentation.

    Git Configuration

    It is recommended to ignore the files generated by Intlayer. This allows you to avoid committing them to your Git repository.

    To do this, you can add the following instructions to your .gitignore file:

    .gitignore
    # Ignore the files generated by Intlayer
    .intlayer
    

    Frequently Asked Questions

    The generic option is i18next with fastify-i18next or a hand written hook, which loads JSON catalogs per namespace and stores the locale on the request. The alternative is Intlayer through fastify-intlayer, which registers the plugin for you, resolves the locale per request, and shares the same typed content as your frontend.

    The reason to internationalize the backend at all is that a large part of the text a user reads never passes through the frontend: API error messages, transactional emails, push notifications, SMS and PDF exports. Those need the recipient's language, resolved per request rather than per session.

    See why Intlayer.

    Very little. Dictionaries are compiled ahead of time and only the locales you declare are included, so there is no catalog loading at boot and no file reads on the request path. That matters most on serverless and edge deployments, where the bundle size drives cold start time. See bundle optimization.

    Yes, and there are two paths. You can migrate the content progressively with the i18next migration guide. Or you can keep your current API entirely: the compat adapters expose the exact same API as i18next, but served by Intlayer dictionaries, so imports change and handler 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 catalogs, 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 catalog one at a time. See the extract command.

    On the frontend side of the same project, the Intlayer Compiler goes further and generates the dictionaries at build time from your JSX, TSX, Vue or Svelte source, so the two halves of the app share one content layer with no keys maintained by hand.

    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.