Getting Started Internationalizing (i18n) with Intlayer and Next.js using Page Router

    What is Intlayer?

    Intlayer is an innovative, open-source internationalization (i18n) library designed to simplify multilingual support in modern web applications. Intlayer seamlessly integrates with the latest Next.js framework, including its traditional Page Router.

    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.

    Intlayer is compatible with Next.js 12, 13, 14, and 15. If you are using Next.js App Router, refer to the App Router guide. For Next.js 15, follow this guide.


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

    Step 1: Install Dependencies

    Install the necessary packages using your preferred package manager:

    bash
    npm install intlayer next-intlayer
    • intlayer

      The core package that provides internationalization 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 internationalization. Additionally, it includes the Next.js plugin for integrating Intlayer with Webpack or Turbopack, as well as middleware for detecting the user's preferred locale, managing cookies, and handling URL redirection.

    Step 2: Configure Your Project

    Create a configuration file to define the languages supported by your application:

    intlayer.config.ts
    import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = {  internationalization: {    locales: [      Locales.ENGLISH,      Locales.FRENCH,      Locales.SPANISH,      // Add your other locales here    ],    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 with Next.js Configuration

    Modify your Next.js configuration to incorporate Intlayer:

    next.config.mjs
    import { withIntlayer } from "next-intlayer/server";/** @type {import('next').NextConfig} */const nextConfig = {  // Your existing Next.js configuration};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 optimize performance and ensures compatibility with server components.

    Step 4: Configure Middleware for Locale Detection

    Set up middleware to automatically detect and handle the user's preferred locale:

    src/middleware.ts
    export { intlayerMiddleware as middleware } from "next-intlayer/middleware";export const config = {  matcher:    "/((?!api|static|assets|robots|sitemap|sw|service-worker|manifest|.*\\..*|_next).*)",};

    Adapt the matcher parameter to match the routes of your application. For more details, refer to the Next.js documentation on configuring the matcher.

    Step 5: Define Dynamic Locale Routes

    Implement dynamic routing to serve localized content based on the user's locale.

    1. Create Locale-Specific Pages:

      Rename your main page file to include the [locale] dynamic segment.

      bash
      mv src/pages/index.tsx src/pages/[locale]/index.tsx
    2. Update _app.tsx to Handle Localization:

      Modify your _app.tsx to include Intlayer providers.

      src/pages/_app.tsx
      import type { FC } from "react";import type { AppProps } from "next/app";import { IntlayerClientProvider } from "next-intlayer";const App: FC<AppProps> = ({ Component, pageProps }) => {  const { locale } = pageProps;  return (    <IntlayerClientProvider locale={locale}>      <Component {...pageProps} />    </IntlayerClientProvider>  );};export default App;
    3. Set Up getStaticPaths and getStaticProps:

      In your [locale]/index.tsx, define the paths and props to handle different locales.

      src/pages/[locale]/index.tsx
      import type { FC } from "react";import type { GetStaticPaths, GetStaticProps } from "next";import { type Locales, getConfiguration } from "intlayer";const HomePage: FC = () => <div>{/* Your content here */}</div>;export const getStaticPaths: GetStaticPaths = () => {  const { internationalization } = getConfiguration();  const { locales } = internationalization;  const paths = locales.map((locale) => ({    params: { locale },  }));  return { paths, fallback: false };};export const getStaticProps: GetStaticProps = ({ params }) => {  const locale = params?.locale as string;  return {    props: {      locale,    },  };};export default HomePage;

    getStaticPaths and getStaticProps ensure that your application pre-builds the necessary pages for all locales in Next.js Page Router. This approach reduces runtime computation and leads to an improved user experience. For more details, refer to the Next.js documentation on getStaticPaths and getStaticProps.

    Step 6: Declare Your Content

    Create and manage your content declarations to store translations.

    src/pages/[locale]/home.content.ts
    import { t, type DeclarationContent } from "intlayer";const homeContent = {  key: "home",  content: {    title: t({      en: "Welcome to My Website",      fr: "Bienvenue sur mon site Web",      es: "Bienvenido a mi sitio web",    }),    description: t({      en: "Get started by editing this page.",      fr: "Commencez par éditer cette page.",      es: "Comience por editar esta página.",    }),  },} satisfies DeclarationContent;export default homeContent;

    For more information on declaring content, refer to the content declaration guide.

    Step 7: Utilize Content in Your Code

    Access your content dictionaries throughout your application to display translated content.

    src/pages/[locale]/index.tsx
    import type { FC } from "react";import { useIntlayer } from "next-intlayer";import { ComponentExample } from "@components/ComponentExample";const HomePage: FC = () => {  const content = useIntlayer("home");  return (    <div>      <h1>{content.title}</h1>      <p>{content.description}</p>      <ComponentExample />      {/* Additional components */}    </div>  );};// ... Rest of the code, including getStaticPaths and getStaticPropsexport default HomePage;
    src/components/ComponentExample.tsx
    import type { FC } from "react";import { useIntlayer } from "next-intlayer";export const ComponentExample: FC = () => {  const content = useIntlayer("component-example"); // Ensure you have a corresponding content declaration  return (    <div>      <h2>{content.title}</h2>      <p>{content.content}</p>    </div>  );};

    When using translations in string attributes (e.g., alt, title, href, aria-label), call the value of the function as follows:

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

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

    (Optional) Step 8: Internationalize Your Metadata

    To internationalize metadata such as page titles and descriptions, use the getStaticProps function in conjunction with Intlayer's getTranslationContent function.

    src/pages/[locale]/index.tsx
    import { GetStaticPaths, GetStaticProps } from "next";import { type IConfigLocales, getTranslationContent, Locales } from "intlayer";import { useIntlayer } from "next-intlayer";interface HomePageProps {  locale: string;  metadata: Metadata;}const HomePage = ({ metadata }: HomePageProps) => {  // Metadata can be used in the head or other components as needed  return (    <div>      <Head>        <title>{metadata.title}</title>        <meta name="description" content={metadata.description} />      </Head>      {/* Additional content */}    </div>  );};export const getStaticProps: GetStaticProps = async ({ params }) => {  const locale = params?.locale as string;  const t = <T,>(content: IConfigLocales<T>) =>    getTranslationContent(content, locale);  const metadata = {    title: t({      en: "My Website",      fr: "Mon Site Web",      es: "Mi Sitio Web",    }),    description: t({      en: "Welcome to my website.",      fr: "Bienvenue sur mon site Web.",      es: "Bienvenido a mi sitio web.",    }),  };  return {    props: {      locale,      metadata,    },  };};export default HomePage;// ... Rest of the code including getStaticPaths

    (Optional) Step 9: Change the Language of Your Content

    To allow users to switch languages dynamically, use the setLocale function provided by the useLocale hook.

    src/components/LanguageSwitcher.tsx
    import {  Locales,  getHTMLTextDir,  getLocaleName,  getLocalizedUrl,} from "intlayer";import { useLocalePageRouter } from "next-intlayer";import { type FC } from "react";const LocaleSwitcher: FC = () => {  const { locale, pathWithoutLocale, availableLocales, setLocale } =    useLocalePageRouter();  return (    <ol>      {availableLocales.map((localeItem) => (        <li key={localeItem}>          <a            href={getLocalizedUrl(pathWithoutLocale, localeItem)}            hrefLang={localeItem}            aria-current={locale === localeItem ? "page" : undefined}            onClick={(e) => {              e.preventDefault();              setLocale(localeItem);            }}          >            <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>            <span>              {/* Language in its own Locale - e.g. FR */}              {localeItem}            </span>          </a>        </li>      ))}    </ol>  );};

    The useLocalePageRouter API is the same as useLocale. To Learn more about the useLocale hook, refer to the documentation.

    Documentation references:

    1. Example of TypeScript Benefits:

      Autocompletion Example

      Translation Error Example

    Git Configuration

    To keep your repository clean and avoid committing generated files, it's recommended to ignore files created by Intlayer.

    Add the following lines to your .gitignore file:

    .gitignore
    # Ignore the files generated by Intlayer.intlayer

    Additional Resources

    By following this guide, you can effectively integrate Intlayer into your Next.js application using the Page Router, enabling robust and scalable internationalization support for your web projects.

    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