Getting Started Internationalizing (i18n) with Intlayer and Vite and React

    What is Intlayer?

    Intlayer is an innovative, open-source internationalization (i18n) library designed to simplify multilingual support in modern web applications.

    With Intlayer, you can:

    • Easily manage translations using declarative dictionaries at the component level.
    • Dynamically localize metadata, routes, and content.
    • Ensure TypeScript support with autogenerated types, improving autocompletion and error detection.
    • Benefit from advanced features, like dynamic locale detection and switching.

    Step-by-Step Guide to Set Up Intlayer in a Vite and React Application

    Step 1: Install Dependencies

    Install the necessary packages using npm:

    bash
    npm install intlayer react-intlayer vite-intlayer
    • intlayer

      The core package that provides internationalization tools for configuration management, translation, content declaration, transpilation, and CLI commands.

    • react-intlayer The package that integrates Intlayer with React application. It provides context providers and hooks for React internationalization.

    • vite-intlayer Includes the Vite plugin for integrating Intlayer with the Vite bundler, as well as middleware for detecting the user's preferred locale, managing cookies, and handling URL redirection.

    Step 2: Configuration of your project

    Create a config file to configure the languages of your application:

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

    Through this configuration file, you can set up localized URLs, middleware redirection, cookie names, the location and extension of your content declarations, disable Intlayer logs in the console, and more. For a complete list of available parameters, refer to the configuration documentation.

    Step 3: Integrate Intlayer in Your Vite Configuration

    Add the intlayer plugin into your configuration.

    vite.config.ts
    import { defineConfig } from "vite";import react from "@vitejs/plugin-react-swc";import { intlayerPlugin } from "vite-intlayer";// https://vitejs.dev/config/export default defineConfig({  plugins: [react(), intlayerPlugin()],});

    The intlayerPlugin() Vite plugin is used to integrate Intlayer with Vite. It ensures the building of content declaration files and monitors them in development mode. It defines Intlayer environment variables within the Vite application. Additionally, it provides aliases to optimize performance.

    Step 4: Declare Your Content

    Create and manage your content declarations to store translations:

    src/app.content.tsx
    import { t, type DeclarationContent } from "intlayer";import type { ReactNode } from "react";const appContent = {  key: "app",  content: {    viteLogo: t({      en: "Vite logo",      fr: "Logo Vite",      es: "Logo Vite",    }),    reactLogo: t({      en: "React logo",      fr: "Logo React",      es: "Logo React",    }),    title: "Vite + React",    count: t({      en: "count is ",      fr: "le compte est ",      es: "el recuento es ",    }),    edit: t<ReactNode>({      // N'oubliez pas d'importer React si vous utilisez un React node dans votre contenu      en: (        <>          Edit <code>src/App.tsx</code> and save to test HMR        </>      ),      fr: (        <>          Éditez <code>src/App.tsx</code> et enregistrez pour tester HMR        </>      ),      es: (        <>          Edita <code>src/App.tsx</code> y guarda para probar HMR        </>      ),    }),    readTheDocs: t({      en: "Click on the Vite and React logos to learn more",      fr: "Cliquez sur les logos Vite et React pour en savoir plus",      es: "Haga clic en los logotipos de Vite y React para obtener más información",    }),  },} satisfies DeclarationContent;export default appContent;

    Your content declarations can be defined anywhere in your application as soon they are included into the contentDir directory (by default, ./src). And match the content declaration file extension (by default, .content.{ts,tsx,js,jsx,mjs,cjs}). For more details, refer to the content declaration documentation. If your content file includes TSX code, you should consider importing import React from "react"; in your content file.

    Step 5: Utilize Intlayer in Your Code

    Access your content dictionaries throughout your application:

    src/App.tsx
    import { useState, type FC } from "react";import reactLogo from "./assets/react.svg";import viteLogo from "/vite.svg";import "./App.css";import { IntlayerProvider, useIntlayer } from "react-intlayer";const AppContent: FC = () => {  const [count, setCount] = useState(0);  const content = useIntlayer("app");  return (    <>      <div>        <a href="https://vitejs.dev" target="_blank">          <img src={viteLogo} className="logo" alt={content.viteLogo.value} />        </a>        <a href="https://react.dev" target="_blank">          <img            src={reactLogo}            className="logo react"            alt={content.reactLogo.value}          />        </a>      </div>      <h1>{content.title}</h1>      <div className="card">        <button onClick={() => setCount((count) => count + 1)}>          {content.count}          {count}        </button>        <p>{content.edit}</p>      </div>      <p className="read-the-docs">{content.readTheDocs}</p>    </>  );};const App: FC = () => (  <IntlayerProvider>    <AppContent />  </IntlayerProvider>);export default App;

    If you want to use your content in a string attribute, such as alt, title, href, aria-label, etc., you must call the value of the function, like:

    jsx
    <img src={content.image.src.value} alt={content.image.value} />

    To Learn more about the useIntlayer hook, refer to the documentation.

    (Optional) Step 6: Change the language of your content

    To change the language of your content, you can use the setLocale function provided by the useLocale hook. This function allows you to set the locale of the application and update the content accordingly.

    src/components/LocaleSwitcher.tsx
    import type { FC } from "react";import { Locales } from "intlayer";import { useLocale } from "react-intlayer";const LocaleSwitcher: FC = () => {  const { setLocale } = useLocale();  return (    <button onClick={() => setLocale(Locales.English)}>      Change Language to English    </button>  );};

    To Learn more about the useLocale hook, refer to the documentation.

    (Optional) Step 7: Add localized Routing to your application

    The purpose of this step is to make unique routes for each language. This is useful for SEO and SEO-friendly URLs. Example:

    plaintext
    - https://example.com/about- https://example.com/es/about- https://example.com/fr/about

    By default, the routes are not prefixed for the default locale. If you want to prefix the default locale, you can set the middleware.prefixDefault option to true in your configuration. See the configuration documentation for more information.

    To add localized routing to your application, you can create a LocaleRouter component that wraps your application's routes and handles locale-based routing. Here is an example using React Router:

    src/components/LocaleRouter.tsx
    // Importing necessary dependencies and functionsimport { Locales, getConfiguration, getPathWithoutLocale } from "intlayer"; // Utility functions and types from 'intlayer'import type { FC, PropsWithChildren } from "react"; // React types for functional components and propsimport { IntlayerProvider } from "react-intlayer"; // Provider for internationalization contextimport {  BrowserRouter,  Routes,  Route,  useParams,  Navigate,  useLocation,} from "react-router-dom"; // Router components for managing navigation// Destructuring configuration from Intlayerconst { internationalization, middleware } = getConfiguration();const { locales, defaultLocale } = internationalization;/** * A component that handles localization and wraps children with the appropriate locale context. * It manages URL-based locale detection and validation. */const AppLocalized: FC<PropsWithChildren> = ({ children }) => {  const path = useLocation().pathname; // Get the current URL path  const { locale } = useParams<{ locale: Locales }>(); // Extract the locale parameter from the URL  // Determine the current locale, falling back to the default if not provided  const currentLocale = locale ?? defaultLocale;  // Remove the locale prefix from the path to construct a base path  const pathWithoutLocale = getPathWithoutLocale(    path // Current URL path  );  /**   * If middleware.prefixDefault is true, the default locale should always be prefixed.   */  if (middleware.prefixDefault) {    // Validate the locale    if (!locale || !locales.includes(locale)) {      // Redirect to the default locale with the updated path      return (        <Navigate          to={`/${defaultLocale}/${pathWithoutLocale}`}          replace // Replace the current history entry with the new one        />      );    }    // Wrap children with the IntlayerProvider and set the current locale    return (      <IntlayerProvider locale={currentLocale}>{children}</IntlayerProvider>    );  } else {    /**     * When middleware.prefixDefault is false, the default locale is not prefixed.     * Ensure that the current locale is valid and not the default locale.     */    if (      currentLocale.toString() !== defaultLocale.toString() &&      !locales        .filter(          (locale) => locale.toString() !== defaultLocale.toString() // Exclude the default locale        )        .includes(currentLocale) // Check if the current locale is in the list of valid locales    ) {      // Redirect to the path without locale prefix      return <Navigate to={pathWithoutLocale} replace />;    }    // Wrap children with the IntlayerProvider and set the current locale    return (      <IntlayerProvider locale={currentLocale}>{children}</IntlayerProvider>    );  }};/** * A router component that sets up locale-specific routes. * It uses React Router to manage navigation and render localized components. */export const LocaleRouter: FC<PropsWithChildren> = ({ children }) => (  <BrowserRouter>    <Routes>      <Route        // Route pattern to capture the locale (e.g., /en/, /fr/) and match all subsequent paths        path="/:locale/*"        element={<AppLocalized>{children}</AppLocalized>} // Wraps children with locale management      />      {        // If prefixing the default locale is disabled, render the children directly at the root path        !middleware.prefixDefault && (          <Route            path="*"            element={<AppLocalized>{children}</AppLocalized>} // Wraps children with locale management          />        )      }    </Routes>  </BrowserRouter>);

    In parallel, you can also use the intLayerMiddlewarePlugin to add server-side routing to your application. This plugin will automatically detect the current locale based on the URL and set the appropriate locale cookie. If no locale is specified, the plugin will determine the most appropriate locale based on the user's browser language preferences. If no locale is detected, it will redirect to the default locale.

    vite.config.ts
    import { defineConfig } from "vite";import react from "@vitejs/plugin-react-swc";import { intlayerPlugin, intLayerMiddlewarePlugin } from "vite-intlayer";// https://vitejs.dev/config/export default defineConfig({  plugins: [react(), intlayerPlugin(), intLayerMiddlewarePlugin()],});

    (Optional) Step 8: Change the URL when the locale changes

    To change the URL when the locale changes, you can use the onLocaleChange prop provided by the useLocale hook. In parallel, you can use the useLocation and useNavigate hooks from react-router-dom to update the URL path.

    src/components/LocaleSwitcher.tsx
    import { useLocation, useNavigate } from "react-router-dom";import {  Locales,  getHTMLTextDir,  getLocaleName,  getLocalizedUrl,} from "intlayer";import { useLocale } from "react-intlayer";import { type FC } from "react";const LocaleSwitcher: FC = () => {  const location = useLocation(); // Get the current URL path. Example: /fr/about  const navigate = useNavigate();  const changeUrl = (locale: Locales) => {    // Construct the URL with the updated locale    // Example: /es/about with the locale set to Spanish    const pathWithLocale = getLocalizedUrl(location.pathname, locale);    // Update the URL path    navigate(pathWithLocale);  };  const { locale, availableLocales, setLocale } = useLocale({    onLocaleChange: changeUrl,  });  return (    <div>      <button popoverTarget="localePopover">{getLocaleName(locale)}</button>      <div id="localePopover" popover="auto">        {availableLocales.map((localeItem) => (          <a            href={getLocalizedUrl(location.pathname, localeItem)}            hrefLang={localeItem}            aria-current={locale === localeItem ? "page" : undefined}            onClick={(e) => {              e.preventDefault();              setLocale(localeItem);            }}            key={localeItem}          >            <span>              {/* Locale - e.g. FR */}              {localeItem}            </span>            <span>              {/* Language in its own Locale - e.g. Français */}              {getLocaleName(localeItem, locale)}            </span>            <span dir={getHTMLTextDir(localeItem)} lang={localeItem}>              {/* Language in current Locale - e.g. Francés with current locale set to Locales.SPANISH */}              {getLocaleName(localeItem)}            </span>            <span dir="ltr" lang={Locales.ENGLISH}>              {/* Language in English - e.g. French */}              {getLocaleName(localeItem, Locales.ENGLISH)}            </span>          </a>        ))}      </div>    </div>  );};

    Documentation references:

    Below is the updated Step 9 with added explanations and refined code examples:


    (Optional) Step 9: Switch the HTML Language and Direction Attributes

    When your application supports multiple languages, it's crucial to update the <html> tag's lang and dir attributes to match the current locale. Doing so ensures:

    • Accessibility: Screen readers and assistive technologies rely on the correct lang attribute to pronounce and interpret content accurately.
    • Text Rendering: The dir (direction) attribute ensures that text is rendered in the proper order (e.g., left-to-right for English, right-to-left for Arabic or Hebrew), which is essential for readability.
    • SEO: Search engines use the lang attribute to determine the language of your page, helping to serve the right localized content in search results.

    By updating these attributes dynamically when the locale changes, you guarantee a consistent and accessible experience for users across all supported languages.

    Implementing the Hook

    Create a custom hook to manage the HTML attributes. The hook listens for locale changes and updates the attributes accordingly:

    src/hooks/useI18nHTMLAttributes.tsx
    import { useEffect } from "react";import { useLocale } from "react-intlayer";import { getHTMLTextDir } from "intlayer";/** * Updates the HTML <html> element's `lang` and `dir` attributes based on the current locale. * - `lang`: Informs browsers and search engines of the page's language. * - `dir`: Ensures the correct reading order (e.g., 'ltr' for English, 'rtl' for Arabic). * * This dynamic update is essential for proper text rendering, accessibility, and SEO. */export const useI18nHTMLAttributes = () => {  const { locale } = useLocale();  useEffect(() => {    // Update the language attribute to the current locale.    document.documentElement.lang = locale;    // Set the text direction based on the current locale.    document.documentElement.dir = getHTMLTextDir(locale);  }, [locale]);};

    Using the Hook in Your Application

    Integrate the hook into your main component so that the HTML attributes update whenever the locale changes:

    src/App.tsx
    import { FC } from "react";import { IntlayerProvider, useIntlayer } from "react-intlayer";import { useI18nHTMLAttributes } from "./hooks/useI18nHTMLAttributes";import "./App.css";const AppContent: FC = () => {  // Apply the hook to update the <html> tag's lang and dir attributes based on the locale.  useI18nHTMLAttributes();  // ... Rest of your component};const App: FC = () => (  <IntlayerProvider>    <AppContent />  </IntlayerProvider>);export default App;

    By applying these changes, your application will:

    • Ensure the language (lang) attribute correctly reflects the current locale, which is important for SEO and browser behavior.
    • Adjust the text direction (dir) according to the locale, enhancing readability and usability for languages with different reading orders.
    • Provide a more accessible experience, as assistive technologies depend on these attributes to function optimally.

    To ensure that your application’s navigation respects the current locale, you can create a custom Link component. This component automatically prefixes internal URLs with the current language, so that. For example, when a French-speaking user clicks on a link to the "About" page, they are redirected to /fr/about instead of /about.

    This behavior is useful for several reasons:

    • SEO and User Experience: Localized URLs help search engines index language-specific pages correctly and provide users with content in their preferred language.
    • Consistency: By using a localized link throughout your application, you guarantee that navigation stays within the current locale, preventing unexpected language switches.
    • Maintainability: Centralizing the localization logic in a single component simplifies the management of URLs, making your codebase easier to maintain and extend as your application grows.

    Below is the implementation of a localized Link component in TypeScript:

    src/components/Link.tsx
    import { getLocalizedUrl } from "intlayer";import {  forwardRef,  type DetailedHTMLProps,  type AnchorHTMLAttributes,} from "react";import { useLocale } from "react-intlayer";export interface LinkProps  extends DetailedHTMLProps<    AnchorHTMLAttributes<HTMLAnchorElement>,    HTMLAnchorElement  > {}/** * Utility function to check whether a given URL is external. * If the URL starts with http:// or https://, it's considered external. */export const checkIsExternalLink = (href?: string): boolean =>  /^https?:\/\//.test(href ?? "");/** * A custom Link component that adapts the href attribute based on the current locale. * For internal links, it uses `getLocalizedUrl` to prefix the URL with the locale (e.g., /fr/about). * This ensures that navigation stays within the same locale context. */export const Link = forwardRef<HTMLAnchorElement, LinkProps>(  ({ href, children, ...props }, ref) => {    const { locale } = useLocale();    const isExternalLink = checkIsExternalLink(href);    // If the link is internal and a valid href is provided, get the localized URL.    const hrefI18n =      href && !isExternalLink ? getLocalizedUrl(href, locale) : href;    return (      <a href={hrefI18n} ref={ref} {...props}>        {children}      </a>    );  });Link.displayName = "Link";

    How It Works

    • Detecting External Links:
      The helper function checkIsExternalLink determines whether a URL is external. External links are left unchanged because they do not need localization.

    • Retrieving the Current Locale:
      The useLocale hook provides the current locale (e.g., fr for French).

    • Localizing the URL:
      For internal links (i.e., non-external), getLocalizedUrl is used to automatically prefix the URL with the current locale. This means that if your user is in French, passing /about as the href will transform it to /fr/about.

    • Returning the Link:
      The component returns an <a> element with the localized URL, ensuring that navigation is consistent with the locale.

    By integrating this Link component across your application, you maintain a coherent and language-aware user experience while also benefitting from improved SEO and usability.

    Configure TypeScript

    Intlayer use module augmentation to get benefits of TypeScript and make your codebase stronger.

    alt text

    alt text

    Ensure your TypeScript configuration includes the autogenerated types.

    tsconfig.json
    {  // your custom config  "include": [    "src",    "types", // <- Include the auto generated types  ],}

    Configure TypeScript

    Intlayer use module augmentation to get benefits of TypeScript and make your codebase stronger.

    alt text

    alt text

    Ensure your TypeScript configuration includes the autogenerated types.

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

    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:

    plaintext
    # Ignore the files generated by Intlayer.intlayer

    Go Further

    To go further, you can implement the visual editor or externalize your content using the CMS.

    If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.

    GitHub link to the documentation