HomeSandboxShowcaseAppDocBlog
    • EnglishEnglish
      EN
    • русскийRussian
      RU
    • 日本語Japanese
      JA
    • françaisFrench
      FR
    • 한국어Korean
      KO
    • 中文Chinese
      ZH
    • españolSpanish
      ES
    • DeutschGerman
      DE
    • العربيةArabic
      AR
    • italianoItalian
      IT
    • British EnglishBritish English
      EN-GB
    • portuguêsPortuguese
      PT
    • हिन्दीHindi
      HI
    • TürkçeTurkish
      TR
    • polskiPolish
      PL
    • IndonesiaIndonesian
      ID
    • Tiếng ViệtVietnamese
      VI
    • українськаUkrainian
      UK
    /
    Filter docs by framework
    Alt+←
    Why Intlayer ?
    Get Started
    Concept
    • How Intlayer Works
    • Configuration
    • TestFillBuildWatchExtractLoginPushPullConfigurationListVersionEditorLiveDebugDoc ReviewDoc TranslateSDK
    • Visual Editor
    • CMS
    • CI/CD Integration
    • TranslationPluralEnumerationConditionGenderInsertionFileNestingMarkdownHTMLFunction Fetching
    • Per Locale File
    • Compiler
    • Auto Fill
    • Testing
    • Bundle Optimization
    Environment
    • Next.js 14 and App Router
      Next.js 15
      Next.js no locale path
      Next.js and Page Router
      Compiler
    • Tanstack Start Solid
    • Astro and React
      Astro and Svelte
      Astro and Vue
      Astro and Solid
      Astro and Preact
      Astro and Lit
      Astro and Vanilla JS
    • React Router v7
      React Router v7 (fs-routes)
      Compiler
    • Nuxt and Vue
    • Vite and Solid
    • SvelteKit
    • Vite and Preact
    • Vite and Vanilla JS
    • Vite and Lit
    • Angular 19 (Webpack)
      Analog
    • React CRA
    • React Native and Expo
    • Express.js
      NestJS
      Fastify
      Hono
      Adonis
    • Lynx and React
    Plugins
    • JSON
    • gettext (.po)
    VS Code Extension
    Agent
    • MCP Server
    • Agent skills
    Releases
    • v8
    • v7
    • v6
    Benchmark
    • Next.js
    • TanStack
    • Vue
    • Solid
    • Svelte
    Blog
    Ask a question
    1. Documentation
    2. Environment
    3. Next.js
    Creation:2024-12-06Last update:2026-05-06
    See the application template on GitHub

    This page has an application template available.

    See the showcase application

    This page links to a live demo of the template.

    Watch the video tutorial

    This page has a video tutorial available.

    Reference this doc to your favorite AI assistant
    ChatGPT
    Claude
    DeepSeek
    Google AI mode
    Gemini
    Perplexity
    Mistral
    Grok

    Ask your question and get a summary of the document by referencing this page and the AI provider of your choice

    Version History

    1. "Update Solid useIntlayer API usage to direct property access"
      v8.9.004/05/2026
    2. "Add init command"
      v7.5.930/12/2025
    3. "Added mention of `x-default` in `alternates` object"
      v7.0.601/11/2025
    4. "Initial history"
      v7.0.029/06/2025

    The content of this page was translated using an AI.

    See the last version of the original content in English
    Edit this doc

    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
    Copy

    Copy doc Markdown to clipboard

    Translate your Next.js 16 website using Intlayer | Internationalisation (i18n)

    www.youtube.com
    ide.intlayer.org
    intlayer-next-16-template.vercel.app

    See Application Template on GitHub.

    Table of Contents

    What is Intlayer?

    Intlayer is an innovative, open-source internationalisation (i18n) library designed to simplify multilingual support in modern web applications. Intlayer seamlessly integrates with the latest Next.js 16 framework, including its powerful App Router. It is optimised to work with Server Components for efficient rendering and is fully compatible with Turbopack.

    With Intlayer, you can:

    • Easily manage translations using declarative dictionaries at the component level.
    • Dynamically localise metadata, routes, and content.
    • Access translations in both client-side and server-side components.
    • Ensure TypeScript support with autogenerated types, improving autocompletion and error detection.
    • Benefit from advanced features, like dynamic locale detection and switching.

    Intlayer is compatible with Next.js 12, 13, 14, and 16. If you are using Next.js Page Router, you can refer to this guide. Locale routing is useful for SEO, bundle size, and performance. If you don't need it, you can refer to this guide. For Next.js 12, 13, 14 with App Router, refer to this guide.


    Step-by-Step Guide to Set Up Intlayer in a Next.js Application

    Step 1: Install Dependencies

    Install the necessary packages using npm:

    bash
    Copy code

    Copy the code to the clipboard

    npm install intlayer next-intlayernpx intlayer init
    • intlayer

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

    • next-intlayer

      The package that integrates Intlayer with Next.js. It provides context providers and hooks for Next.js internationalisation. Additionally, it includes the Next.js plugin for integrating Intlayer with Webpack or Turbopack, as well as proxy for detecting the user's preferred locale, managing cookies, and handling URL redirection.

    Step 2: Configure Your Project

    Here is the final structure that we will make:

    bash
    Copy code

    Copy the code to the clipboard

    .├── src│   ├── app│   │   ├── [locale]│   │   │   ├── layout.tsx            # Locale layout for the Intlayer provider│   │   │   ├── page.content.ts│   │   │   └── page.tsx│   │   └── layout.tsx                # Root layout for style and global providers│   ├── components│   │   ├── client-component-example.content.ts│   │   ├── ClientComponentExample.tsx│   │   ├── LocaleSwitcher│   │   │   ├── localeSwitcher.content.ts│   │   │   └── LocaleSwitcher.tsx│   │   ├── server-component-example.content.ts│   │   └── ServerComponentExample.tsx│   └── proxy.ts├── intlayer.config.ts├── next.config.ts├── package.json└── tsconfig.json
    If you don't want locale routing, intlayer can be used as a simple provider / hook. See this guide for more details.

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

    intlayer.config.ts
    Copy code

    Copy the code to the clipboard

    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 localised URLs, proxy 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 Next.js Configuration

    Configure your Next.js setup to use Intlayer:

    next.config.ts
    Copy code

    Copy the code to the clipboard

    import type { NextConfig } from "next";
    import { withIntlayer } from "next-intlayer/server";
    
    const nextConfig: NextConfig = {
      /* config options here */
    };
    
    export default withIntlayer(nextConfig);
    The withIntlayer() Next.js plugin is used to integrate Intlayer with Next.js. It ensures the building of content declaration files and monitors them in development mode. It defines Intlayer environment variables within the Webpack or Turbopack environments. Additionally, it provides aliases to optimise performance and ensures compatibility with server components.

    The withIntlayer() function is a promise function. It allows to prepare the intlayer dictionaries before the build starts. If you want to use it with other plugins, you can await it. Example:

    ts
    Copy code

    Copy the code to the clipboard

    const nextConfig = await withIntlayer(nextConfig);const nextConfigWithOtherPlugins = withOtherPlugins(nextConfig);export default nextConfigWithOtherPlugins;

    If you want to use it synchronously, you can use the withIntlayerSync() function. Example:

    ts
    Copy code

    Copy the code to the clipboard

    const nextConfig = withIntlayerSync(nextConfig);const nextConfigWithOtherPlugins = withOtherPlugins(nextConfig);export default nextConfigWithOtherPlugins;

    Intlayer automatically detects whether your project is using webpack or Turbopack based on the command-line flags --webpack, --turbo, or --turbopack, as well as your current Next.js version.

    Since next>=16, if you are using Rspack, you must explicitly force Intlayer to use the webpack configuration by disabling Turbopack:

    ts
    Copy code

    Copy the code to the clipboard

    withRspack(withIntlayer(nextConfig, { enableTurbopack: false }));

    Step 4: Define Dynamic Locale Routes

    Remove everything from RootLayout and replace it with the following code:

    src/app/layout.tsx
    Copy code

    Copy the code to the clipboard

    import type { PropsWithChildren, FC } from "react";
    import "./globals.css";
    
    const RootLayout: FC<PropsWithChildren> = ({ children }) => (
      // You can still wrap the children with other providers, Like `next-themes`, `react-query`, `framer-motion`, etc.
      <>{children}</>
    );
    
    export default RootLayout;
    Keeping the RootLayout component empty allows to set the lang and dir attributes to the <html> tag.

    To implement dynamic routing, provide the path for the locale by adding a new layout in your [locale] directory:

    src/app/[locale]/layout.tsx
    Copy code

    Copy the code to the clipboard

    import { type NextLayoutIntlayer, IntlayerClientProvider } from "next-intlayer";
    import { Inter } from "next/font/google";
    import { getHTMLTextDir } from "intlayer";
    
    const inter = Inter({ subsets: ["latin"] });
    
    const LocaleLayout: NextLayoutIntlayer = async ({ children, params }) => {
      const { locale } = await params;
      return (
        <html lang={locale} dir={getHTMLTextDir(locale)}>
          <body className={inter.className}>
            <IntlayerClientProvider locale={locale}>
              {children}
            </IntlayerClientProvider>
          </body>
        </html>
      );
    };
    
    export default LocaleLayout;
    The [locale] path segment is used to define the locale. Example: /en-GB/about will refer to en-GB and /fr/about to fr.
    At this stage, you will encounter the error: Error: Missing <html> and <body> tags in the root layout.. This is expected because the /app/page.tsx file is no longer in use and can be removed. Instead, the [locale] path segment will activate the /app/[locale]/page.tsx page. Consequently, pages will be accessible via paths like /en, /fr, /es in your browser. To set the default locale as the root page, refer to the proxy setup in step 7.

    Then, implement the generateStaticParams function in your application Layout.

    src/app/[locale]/layout.tsx
    Copy code

    Copy the code to the clipboard

    export { generateStaticParams } from "next-intlayer"; // Line to insert
    
    const LocaleLayout: NextLayoutIntlayer = async ({ children, params }) => {
      /*... Rest of the code*/
    };
    
    export default LocaleLayout;
    generateStaticParams ensures that your application pre-builds the necessary pages for all locales, reducing runtime computation and improving the user experience. For more details, refer to the Next.js documentation on generateStaticParams.
    Intlayer works with export const dynamic = 'force-static'; to ensure that the pages are pre-built for all locales.

    Step 5: Declare Your Content

    Create and manage your content declarations to store translations:

    src/app/[locale]/page.content.ts
    Copy code

    Copy the code to the clipboard

    import { t, type Dictionary } from "intlayer";
    
    const pageContent = {
      key: "page",
      content: {
        getStarted: {
          main: t({
            en: "Get started by editing",
            fr: "Commencez par éditer",
            es: "Comience por editar",
          }),
          pageLink: "src/app/page.tsx",
        },
      },
    } satisfies Dictionary;
    
    export default pageContent;
    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.{json,ts,tsx,js,jsx,mjs,cjs}).
    For more details, refer to the content declaration documentation.

    Step 6: Utilise Content in Your Code

    Access your content dictionaries throughout your application:

    src/app/[locale]/page.tsx
    Copy code

    Copy the code to the clipboard

    import type { FC } from "react";
    import { ClientComponentExample } from "@components/ClientComponentExample";
    import { ServerComponentExample } from "@components/ServerComponentExample";
    import { type NextPageIntlayer } from "next-intlayer";
    import { IntlayerServerProvider, useIntlayer } from "next-intlayer/server";
    
    const PageContent: FC = () => {
      const content = useIntlayer("page");
    
      return (
        <>
          <p>{content.getStarted.main}</p>
          <code>{content.getStarted.pageLink}</code>
        </>
      );
    };
    
    const Page: NextPageIntlayer = async ({ params }) => {
      const { locale } = await params;
    
      return (
        <IntlayerServerProvider locale={locale}>
          <PageContent />
          <ServerComponentExample />
    
          <ClientComponentExample />
        </IntlayerServerProvider>
      );
    };
    
    export default Page;
    • IntlayerClientProvider is used to provide the locale to client-side components. It can be placed in any parent component, including the layout. However, placing it in a layout is recommended because Next.js shares layout code across pages, making it more efficient. By using IntlayerClientProvider in the layout, you avoid reinitialising it for every page, improving performance and maintaining a consistent localisation context throughout your application.
    • IntlayerServerProvider is used to provide the locale to the server children. It cannot be set set in the layout.

      Layout and page cannot share a common server context because the server context system is based on a per-request data store (via React's cache mechanism), causing each "context" to be re-created for different segments of the application. Placing the provider in a shared layout would break this isolation, preventing the correct propagation of the server context values to your server components.
    src/components/ClientComponentExample.tsx
    Copy code

    Copy the code to the clipboard

    "use client";
    
    import type { FC } from "react";
    import { useIntlayer } from "next-intlayer";
    
    export const ClientComponentExample: FC = () => {
      const content = useIntlayer("client-component-example"); // Create related content declaration
    
      return (
        <div>
          <h2>{content.title}</h2>
          <p>{content.content}</p>
        </div>
      );
    };
    src/components/ServerComponentExample.tsx
    Copy code

    Copy the code to the clipboard

    import type { FC } from "react";
    import { useIntlayer } from "next-intlayer/server";
    
    export const ServerComponentExample: FC = () => {
      const content = useIntlayer("server-component-example"); // Create related content declaration
    
      return (
        <div>
          <h2>{content.title}</h2>
          <p>{content.content}</p>
        </div>
      );
    };
    If you want to use your content in a string attribute, such as alt, title, href, aria-label, etc., you can use the value of the function, like:
    html
    Copy code

    Copy the code to the clipboard

    <img src="{content.image.src.value}" alt="{content.image.value}" /><img src="{content.image.src.toString()}" alt="{content.image.toString()}" /><img src="{String(content.image.src)}" alt="{String(content.image)}" />
    To Learn more about the useIntlayer hook, refer to the documentation.

    (Optional) Step 7: Configure Proxy for Locale Detection

    Set up proxy to detect the user's preferred locale:

    src/proxy.ts
    Copy code

    Copy the code to the clipboard

    export { intlayerProxy as proxy } from "next-intlayer/proxy";
    
    export const config = {
      matcher:
        "/((?!api|static|assets|robots|sitemap|sw|service-worker|manifest|.*\\..*|_next).*)",
    };
    The intlayerProxy is used to detect the user's preferred locale and redirect them to the appropriate URL as specified in the configuration. Additionally, it enables saving the user's preferred locale in a cookie.
    If you need to chain several proxies together (for example, intlayerProxy with authentication or custom proxies), Intlayer now provides a helper called multipleProxies.
    ts
    Copy code

    Copy the code to the clipboard

    import { multipleProxies, intlayerProxy } from "next-intlayer/proxy";import { customProxy } from "@utils/customProxy";export const proxy = multipleProxies([intlayerProxy, customProxy]);

    (Optional) Step 8: Internationalisation of your metadata

    In the case you want to internationalise your metadata, such as the title of your page, you can use the generateMetadata function provided by Next.js. Inside, you can retrieve the content from the getIntlayer function to translate your metadata.

    src/app/[locale]/metadata.content.ts
    Copy code

    Copy the code to the clipboard

    import { type Dictionary, t } from "intlayer";
    import { Metadata } from "next";
    
    const metadataContent = {
      key: "page-metadata",
      content: {
        title: t({
          en: "Create Next App",
          fr: "Créer une application Next.js",
          es: "Crear una aplicación Next.js",
        }),
        description: t({
          en: "Generated by create next app",
          fr: "Généré par create next app",
          es: "Generado por create next app",
        }),
      },
    } satisfies Dictionary<Metadata>;
    
    export default metadataContent;
    src/app/[locale]/layout.tsx or src/app/[locale]/page.tsx
    Copy code

    Copy the code to the clipboard

    import { getIntlayer, getMultilingualUrls } from "intlayer";
    import type { Metadata } from "next";
    import type { LocalPromiseParams } from "next-intlayer";
    
    export const generateMetadata = async ({
      params,
    }: LocalPromiseParams): Promise<Metadata> => {
      const { locale } = await params;
    
      const metadata = getIntlayer("page-metadata", locale);
    
      /**
       * Generates an object containing all url for each locale.
       *
       * Example:
       * ```ts
       *  getMultilingualUrls('/about');
       *
       *  // Returns
       *  // {
       *  //   en: '/about',
       *  //   fr: '/fr/about',
       *  //   es: '/es/about',
       *  // }
       * ```
       */
      const multilingualUrls = getMultilingualUrls("/");
      const localizedUrl =
        multilingualUrls[locale as keyof typeof multilingualUrls];
    
      return {
        ...metadata,
        alternates: {
          canonical: localizedUrl,
          languages: { ...multilingualUrls, "x-default": "/" },
        },
        openGraph: {
          url: localizedUrl,
        },
      };
    };
    
    // ... Rest of the code
    Note that the getIntlayer function imported from next-intlayer returns your content wrapped in an IntlayerNode, allowing integration with the visual editor. In contrast, the getIntlayer function imported from intlayer returns your content directly without additional properties.

    Alternatively, you can use the getTranslation function to declare your metadata. However, using content declaration files is recommended to automate the translation of your metadata and externalize the content at some point.

    src/app/[locale]/layout.tsx or src/app/[locale]/page.tsx
    Copy code

    Copy the code to the clipboard

    import {
      type IConfigLocales,
      getTranslation,
      getMultilingualUrls,
    } from "intlayer";
    import type { Metadata } from "next";
    import type { LocalPromiseParams } from "next-intlayer";
    
    export const generateMetadata = async ({
      params,
    }: LocalPromiseParams): Promise<Metadata> => {
      const { locale } = await params;
      const t = <T>(content: IConfigLocales<T>) => getTranslation(content, locale);
    
      return {
        title: t<string>({
          en: "My title",
          fr: "Mon titre",
          es: "Mi título",
        }),
        description: t({
          en: "My description",
          fr: "Ma description",
          es: "Mi descripción",
        }),
      };
    };
    
    // ... Rest of the code
    Learn more about the metadata optimisation on the official Next.js documentation.

    (Optional) Step 9: Internationalisation of your sitemap.xml and robots.txt

    To internationalise your sitemap.xml and robots.txt, you can use the getMultilingualUrls function provided by Intlayer. This function allows you to generate multilingual URLs for your sitemap.

    src/app/sitemap.ts
    Copy code

    Copy the code to the clipboard

    import { getMultilingualUrls } from "intlayer";
    import type { MetadataRoute } from "next";
    
    const sitemap = (): MetadataRoute.Sitemap => [
      {
        url: "https://example.com",
        alternates: {
          languages: {
            ...getMultilingualUrls("https://example.com"),
            "x-default": "https://example.com",
          },
        },
      },
      {
        url: "https://example.com/login",
        alternates: {
          languages: {
            ...getMultilingualUrls("https://example.com/login"),
            "x-default": "https://example.com/login",
          },
        },
      },
      {
        url: "https://example.com/register",
        alternates: {
          languages: {
            ...getMultilingualUrls("https://example.com/register"),
            "x-default": "https://example.com/register",
          },
        },
      },
    ];
    
    export default sitemap;
    src/app/robots.ts
    Copy code

    Copy the code to the clipboard

    import type { MetadataRoute } from "next";
    import { getMultilingualUrls } from "intlayer";
    
    const getAllMultilingualUrls = (urls: string[]) =>
      urls.flatMap((url) => Object.values(getMultilingualUrls(url)) as string[]);
    
    const robots = (): MetadataRoute.Robots => ({
      rules: {
        userAgent: "*",
        allow: ["/"],
        disallow: getAllMultilingualUrls(["/login", "/register"]),
      },
      host: "https://example.com",
      sitemap: `https://example.com/sitemap.xml`,
    });
    
    export default robots;
    Learn more about the sitemap optimisation on the official Next.js documentation. Learn more about the robots.txt optimisation on the official Next.js documentation.

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

    To change the language of your content in Next.js, the recommended way is to use the Link component to redirect users to the appropriate localised page. The Link component enables prefetching of the page, which helps avoid a full page reload.

    src/components/LocaleSwitcher.tsx
    Copy code

    Copy the code to the clipboard

    "use client";
    
    import type { FC } from "react";
    import {
      Locales,
      getHTMLTextDir,
      getLocaleName,
      getLocalizedUrl,
    } from "intlayer";
    import { useLocale } from "next-intlayer";
    import Link from "next/link";
    
    export const LocaleSwitcher: FC = () => {
      const { locale, pathWithoutLocale, availableLocales, setLocale } =
        useLocale();
    
      return (
        <div>
          <button popoverTarget="localePopover">{getLocaleName(locale)}</button>
          <div id="localePopover" popover="auto">
            {availableLocales.map((localeItem) => (
              <Link
                href={getLocalizedUrl(pathWithoutLocale, localeItem)}
                key={localeItem}
                aria-current={locale === localeItem ? "page" : undefined}
                onClick={() => setLocale(localeItem)}
                replace // Will ensure that the "go back" browser button will redirect to the previous page
              >
                <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>
              </Link>
            ))}
          </div>
        </div>
      );
    };
    An alternative way is to use the setLocale function provided by the useLocale hook. This function will not allow prefetching the page. See the useLocale hook documentation for more details.
    You can also set a function in the onLocaleChange option to trigger a custom function when the locale changes.
    src/components/LocaleSwitcher.tsx
    Copy code

    Copy the code to the clipboard

    "use client";import { useRouter } from "next/navigation";import { useLocale } from "next-intlayer";import { getLocalizedUrl } from "intlayer";// ... Rest of the codeconst router = useRouter();const { setLocale } = useLocale({  onLocaleChange: (locale) => {    router.push(getLocalizedUrl(pathWithoutLocale, locale));  },});return (  <button onClick={() => setLocale(Locales.FRENCH)}>Change to French</button>);

    Documentation references:

    • useLocale hook
    • getLocaleName hook
    • getLocalizedUrl hook
    • getHTMLTextDir hook
    • hrefLang attribute
    • lang attribute
    • dir attribute`
    • aria-current attribute

    (Optional) Step 11: Creating a Localised Link Component

    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. 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 behaviour is useful for several reasons:

    • SEO and User Experience: Localised URLs help search engines index language-specific pages correctly and provide users with content in their preferred language.
    • Consistency: By using a localised link throughout your application, you guarantee that navigation stays within the current locale, preventing unexpected language switches.
    • Maintainability: Centralising the localisation 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 localised Link component in TypeScript:

    src/components/Link.tsx
    Copy code

    Copy the code to the clipboard

    "use client";
    
    import { getLocalizedUrl } from "intlayer";
    import NextLink, { type LinkProps as NextLinkProps } from "next/link";
    import { useLocale } from "next-intlayer";
    import type { PropsWithChildren, FC } from "react";
    
    /**
     * 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: FC<PropsWithChildren<NextLinkProps>> = ({
      href,
      children,
      ...props
    }) => {
      const { locale } = useLocale();
      const isExternalLink = checkIsExternalLink(href.toString());
    
      // If the link is internal and a valid href is provided, get the localised URL.
      const hrefI18n: NextLinkProps["href"] =
        href && !isExternalLink ? getLocalizedUrl(href.toString(), locale) : href;
    
      return (
        <NextLink href={hrefI18n} {...props}>
          {children}
        </NextLink>
      );
    };

    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 localisation.

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

    • Localising 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 localised 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.

    (Optional) Step 12: Get the current locale in Server Actions

    If you need the active locale inside a Server Action (e.g., to localise emails or run locale-aware logic), call getLocale from next-intlayer/server:

    src/app/actions/getLocale.ts
    Copy code

    Copy the code to the clipboard

    "use server";import { getLocale } from "next-intlayer/server";export const myServerAction = async () => {  const locale = await getLocale();  // Do something with the locale};

    The getLocale function follows a cascading strategy to determine the user's locale:

    1. First, it checks the request headers for a locale value that may have been set by the proxy
    2. If no locale is found in headers, it looks for a locale stored in cookies
    3. If no cookie is found, it attempts to detect the user's preferred language from their browser settings
    4. As a last resort, it falls back to the application's configured default locale

    This ensures the most appropriate locale is selected based on available context.

    (Optional) Step 13: Optimise your bundle size

    When using next-intlayer, dictionaries are included in the bundle for every page by default. To optimise bundle size, Intlayer provides an optional SWC plugin that intelligently replace useIntlayer calls using macros. This ensures dictionaries are only included in bundles for pages that actually use them.

    To enable this optimisation, install the @intlayer/swc package. Once installed, next-intlayer will automatically detect and use the plugin:

    bash
    Copy code

    Copy the code to the clipboard

    npm install @intlayer/swc --save-dev
    Note: This optimisation is only available for Next.js 13 and above.
    Note: This package is not installed by default because SWC plugins are still experimental on Next.js. It may change in the future.
    Note: If you set the option as importMode: 'dynamic' or importMode: 'fetch' (in the dictionary configuration), it will rely on Suspense, so you will have to wrap your useIntlayer calls in a Suspense boundary. That means, you will not be able to use the useIntlayer directly at the top level of your Page / Layout component.

    Watch dictionaries changes on Turbopack

    When using Turbopack as your development server with the next dev command, dictionary changes will not be automatically detected by default.

    This limitation occurs because Turbopack cannot run webpack plugins in parallel to monitor changes in your content files. To work around this, you'll need to use the intlayer watch command to run both the development server and the Intlayer build watcher simultaneously.

    package.json
    Copy code

    Copy the code to the clipboard

    {  // ... Your existing package.json configurations  "scripts": {    // ... Your existing scripts configurations    "dev": "intlayer watch --with 'next dev'",  },}
    If you are using next-intlayer@<=6.x.x, you need to keep the --turbopack flag to make the Next.js 16 application work correctly with Turbopack. We recommend using next-intlayer@>=7.x.x to avoid this limitation.

    Configure TypeScript

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

    Autocompletion

    Translation error

    Ensure your TypeScript configuration includes the autogenerated types.

    tsconfig.json
    Copy code

    Copy the code to the clipboard

    {  // ... 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:

    .gitignore
    Copy code

    Copy the code to the clipboard

    # Ignore the files generated by Intlayer.intlayer

    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.

    Go Further

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

    Bundle Optimization
    Next.js 14 and App Router
    Alt+→

    On this page

      Discussions are anonymous and regularly reviewed to address common issues. Feel free to share feature ideas, feedback on the documentation, or anything related to Intlayer, we use this input to shape our roadmap and improve the product.

      npm install intlayer next-intlayernpx intlayer init
      .├── src│   ├── app│   │   ├── [locale]│   │   │   ├── layout.tsx            # Locale layout for the Intlayer provider│   │   │   ├── page.content.ts│   │   │   └── page.tsx│   │   └── layout.tsx                # Root layout for style and global providers│   ├── components│   │   ├── client-component-example.content.ts│   │   ├── ClientComponentExample.tsx│   │   ├── LocaleSwitcher│   │   │   ├── localeSwitcher.content.ts│   │   │   └── LocaleSwitcher.tsx│   │   ├── server-component-example.content.ts│   │   └── ServerComponentExample.tsx│   └── proxy.ts├── intlayer.config.ts├── next.config.ts├── package.json└── tsconfig.json
      const nextConfig = await withIntlayer(nextConfig);const nextConfigWithOtherPlugins = withOtherPlugins(nextConfig);export default nextConfigWithOtherPlugins;
      const nextConfig = withIntlayerSync(nextConfig);const nextConfigWithOtherPlugins = withOtherPlugins(nextConfig);export default nextConfigWithOtherPlugins;
      withRspack(withIntlayer(nextConfig, { enableTurbopack: false }));
      <img src="{content.image.src.value}" alt="{content.image.value}" /><img src="{content.image.src.toString()}" alt="{content.image.toString()}" /><img src="{String(content.image.src)}" alt="{String(content.image)}" />
      import { multipleProxies, intlayerProxy } from "next-intlayer/proxy";import { customProxy } from "@utils/customProxy";export const proxy = multipleProxies([intlayerProxy, customProxy]);
      "use client";import { useRouter } from "next/navigation";import { useLocale } from "next-intlayer";import { getLocalizedUrl } from "intlayer";// ... Rest of the codeconst router = useRouter();const { setLocale } = useLocale({  onLocaleChange: (locale) => {    router.push(getLocalizedUrl(pathWithoutLocale, locale));  },});return (  <button onClick={() => setLocale(Locales.FRENCH)}>Change to French</button>);
      "use server";import { getLocale } from "next-intlayer/server";export const myServerAction = async () => {  const locale = await getLocale();  // Do something with the locale};
      npm install @intlayer/swc --save-dev
      {  // ... Your existing package.json configurations  "scripts": {    // ... Your existing scripts configurations    "dev": "intlayer watch --with 'next dev'",  },}
      {  // ... Your existing TypeScript configurations  "include": [    // ... Your existing TypeScript configurations    ".intlayer/**/*.ts", // Include the auto-generated types  ],}
      # Ignore the files generated by Intlayer.intlayer