1. Documentation
    2. Environment
    3. Intlayer with Next.js
    4. Next.js and Page Router

    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
    1npm install intlayer next-intlayer
    bash
    1yarn add intlayer next-intlayer
    bash
    1pnpm add intlayer next-intlayer

    Step 2: Configure Your Project

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

    typescript
    1// intlayer.config.ts 2 3import { Locales, type IntlayerConfig } from "intlayer"; 4 5const config: IntlayerConfig = { 6 internationalization: { 7 locales: [ 8 Locales.ENGLISH, 9 Locales.FRENCH, 10 Locales.SPANISH, 11 // Add your other locales here 12 ], 13 defaultLocale: Locales.ENGLISH, 14 }, 15}; 16 17export 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
    1// next.config.mjs 2import { withIntlayer } from "next-intlayer/server"; 3 4/** @type {import('next').NextConfig} */ 5const nextConfig = { 6 // Your existing Next.js configuration 7}; 8 9export default withIntlayer(nextConfig);

    Step 4: Configure Middleware for Locale Detection

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

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

    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
      1mv 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
      1// src/pages/_app.tsx 2 3import { AppProps } from "next/app"; 4import { IntlayerClientProvider } from "next-intlayer"; 5import { IntlayerServerProvider } from "next-intlayer/server"; 6import intlayerConfig from "../../intlayer.config"; 7 8function MyApp({ Component, pageProps }: AppProps) { 9 const { locale } = pageProps; 10 11 return ( 12 <IntlayerClientProvider locale={locale}> 13 <Component {...pageProps} /> 14 </IntlayerClientProvider> 15 ); 16} 17 18export default MyApp;
    3. Set Up getStaticPaths and getStaticProps:

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

      tsx
      1// src/pages/[locale]/index.tsx 2 3import { GetStaticPaths, GetStaticProps } from "next"; 4import { useIntlayer } from "next-intlayer"; 5import { Locales } from "intlayer"; 6 7const HomePage = () => { 8 return <div>{/* Your content here */}</div>; 9}; 10 11export const getStaticPaths: GetStaticPaths = async () => { 12 const locales = [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH]; // Add your locales here 13 14 const paths = locales.map((locale) => ({ 15 params: { locale }, 16 })); 17 18 return { paths, fallback: false }; 19}; 20 21export const getStaticProps: GetStaticProps = async ({ params }) => { 22 const locale = params?.locale as string; 23 24 return { 25 props: { 26 locale, 27 }, 28 }; 29}; 30 31export default HomePage;

    Step 6: Declare Your Content

    Create and manage your content dictionaries to store translations.

    tsx
    1// src/pages/[locale]/home.content.ts 2import { t, type DeclarationContent } from "intlayer"; 3 4const homeContent = { 5 key: "home", 6 content: { 7 title: t({ 8 en: "Welcome to My Website", 9 fr: "Bienvenue sur mon site Web", 10 es: "Bienvenido a mi sitio web", 11 }), 12 description: t({ 13 en: "Get started by editing this page.", 14 fr: "Commencez par éditer cette page.", 15 es: "Comience por editar esta página.", 16 }), 17 }, 18} satisfies DeclarationContent; 19 20export 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
    1// src/pages/[locale]/index.tsx 2 3import { GetStaticPaths, GetStaticProps } from "next"; 4import { useIntlayer } from "next-intlayer"; 5import { Locales } from "intlayer"; 6import { ComponentExample } from "@component/ComponentExample"; 7 8const HomePage = () => { 9 const content = useIntlayer("home"); 10 11 return ( 12 <div> 13 <h1>{content.title}</h1> 14 <p>{content.description}</p> 15 <ComponentExample /> 16 {/* Additional components */} 17 </div> 18 ); 19}; 20 21// ... Rest of the code, including getStaticPaths and getStaticProps 22 23export default HomePage;
    tsx
    1// src/components/ComponentExample.tsx 2 3import { useIntlayer } from "next-intlayer"; 4 5export const ComponentExample = () => { 6 const content = useIntlayer("client-component-example"); // Ensure you have a corresponding content declaration 7 8 return ( 9 <div> 10 <h2>{content.title}</h2> 11 <p>{content.content}</p> 12 </div> 13 ); 14};

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

    tsx
    1<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
    1// src/pages/[locale]/index.tsx 2 3import { GetStaticPaths, GetStaticProps } from "next"; 4import { type IConfigLocales, getTranslationContent, Locales } from "intlayer"; 5import { useIntlayer } from "next-intlayer"; 6 7interface HomePageProps { 8 locale: string; 9 metadata: Metadata; 10} 11 12const HomePage = ({ metadata }: HomePageProps) => { 13 // Metadata can be used in the head or other components as needed 14 return ( 15 <div> 16 <Head> 17 <title>{metadata.title}</title> 18 <meta name="description" content={metadata.description} /> 19 </Head> 20 21 {/* Additional content */} 22 </div> 23 ); 24}; 25 26export const getStaticProps: GetStaticProps = async ({ params }) => { 27 const locale = params?.locale as string; 28 29 const t = <T,>(content: IConfigLocales<T>) => 30 getTranslationContent(content, locale); 31 32 const metadata = { 33 title: t({ 34 en: "My Website", 35 fr: "Mon Site Web", 36 es: "Mi Sitio Web", 37 }), 38 description: t({ 39 en: "Welcome to my website.", 40 fr: "Bienvenue sur mon site Web.", 41 es: "Bienvenido a mi sitio web.", 42 }), 43 }; 44 45 return { 46 props: { 47 locale, 48 metadata, 49 }, 50 }; 51}; 52 53export default HomePage; 54 55// ... 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
    1// src/components/LanguageSwitcher.tsx 2 3import { Locales } from "intlayer"; 4import { useLocalePageRouter } from "next-intlayer"; 5 6const LanguageSwitcher = () => { 7 const { setLocale } = useLocalePageRouter(); 8 9 return ( 10 <div> 11 <button onClick={() => setLocale(Locales.ENGLISH)}>English</button> 12 <button onClick={() => setLocale(Locales.FRENCH)}>Français</button> 13 <button onClick={() => setLocale(Locales.SPANISH)}>Español</button> 14 {/* Add more buttons for additional locales */} 15 </div> 16 ); 17}; 18 19export 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
      1// tsconfig.json 2 3{ 4 "compilerOptions": { 5 // Your existing TypeScript configurations 6 }, 7 "include": [ 8 "src", 9 "types" // Include the auto-generated types 10 ] 11}
    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
      1# Ignore the files generated by Intlayer 2.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

    In this page