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.

    Note: 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
    
    bash
    yarn add intlayer next-intlayer
    
    bash
    pnpm add intlayer next-intlayer
    

    Step 2: Configure Your Project

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

    typescript
    // 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;
    

    For a complete list of available configuration options, refer to the configuration documentation.

    Step 3: Integrate Intlayer with Next.js Configuration

    Modify your Next.js configuration to incorporate Intlayer:

    typescript
    // next.config.mjs
    import { withIntlayer } from "next-intlayer/server";
    
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      // Your existing Next.js configuration
    };
    
    export default withIntlayer(nextConfig);
    

    Step 4: Configure Middleware for Locale Detection

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

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

    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.

      tsx
      // src/pages/_app.tsx
      
      import { AppProps } from "next/app";
      import { IntlayerClientProvider } from "next-intlayer";
      import { IntlayerServerProvider } from "next-intlayer/server";
      import intlayerConfig from "../../intlayer.config";
      
      function MyApp({ Component, pageProps }: AppProps) {
        const { locale } = pageProps;
      
        return (
          <IntlayerClientProvider locale={locale}>
            <Component {...pageProps} />
          </IntlayerClientProvider>
        );
      }
      
      export default MyApp;
      
    3. Set Up getStaticPaths and getStaticProps:

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

      tsx
      // src/pages/[locale]/index.tsx
      
      import { GetStaticPaths, GetStaticProps } from "next";
      import { useIntlayer } from "next-intlayer";
      import { Locales } from "intlayer";
      
      const HomePage = () => {
        return <div>{/* Your content here */}</div>;
      };
      
      export const getStaticPaths: GetStaticPaths = async () => {
        const locales = [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH]; // Add your locales here
      
        const paths = locales.map((locale) => ({
          params: { locale },
        }));
      
        return { paths, fallback: false };
      };
      
      export const getStaticProps: GetStaticProps = async ({ params }) => {
        const locale = params?.locale as string;
      
        return {
          props: {
            locale,
          },
        };
      };
      
      export default HomePage;
      

    Step 6: Declare Your Content

    Create and manage your content dictionaries to store translations.

    tsx
    // 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.

    tsx
    // src/pages/[locale]/index.tsx
    
    import { GetStaticPaths, GetStaticProps } from "next";
    import { useIntlayer } from "next-intlayer";
    import { Locales } from "intlayer";
    import { ComponentExample } from "@component/ComponentExample";
    
    const HomePage = () => {
      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 getStaticProps
    
    export default HomePage;
    
    tsx
    // src/components/ComponentExample.tsx
    
    import { useIntlayer } from "next-intlayer";
    
    export const ComponentExample = () => {
      const content = useIntlayer("client-component-example"); // Ensure you have a corresponding content declaration
    
      return (
        <div>
          <h2>{content.title}</h2>
          <p>{content.content}</p>
        </div>
      );
    };
    

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

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

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

    tsx
    // 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.

    tsx
    // src/components/LanguageSwitcher.tsx
    
    import { Locales } from "intlayer";
    import { useLocalePageRouter } from "next-intlayer";
    
    const LanguageSwitcher = () => {
      const { setLocale } = useLocalePageRouter();
    
      return (
        <div>
          <button onClick={() => setLocale(Locales.ENGLISH)}>English</button>
          <button onClick={() => setLocale(Locales.FRENCH)}>Français</button>
          <button onClick={() => setLocale(Locales.SPANISH)}>Español</button>
          {/* Add more buttons for additional locales */}
        </div>
      );
    };
    
    export default LanguageSwitcher;
    

    Configure TypeScript

    Intlayer uses module augmentation to enhance TypeScript's capabilities, providing better type safety and autocompletion.

    1. Ensure TypeScript Includes Autogenerated Types:

      Update your tsconfig.json to include the autogenerated types.

      json
      // tsconfig.json
      
      {
        "compilerOptions": {
          // Your existing TypeScript configurations
        },
        "include": [
          "src",
          "types" // Include the auto-generated types
        ]
      }
      
    2. 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.

    1. Update .gitignore:

      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