1. Documentation
    2. Environment
    3. Intlayer with Next.js

    Getting Started internationalizing (i18n) with Intlayer and Next.js 15 App 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 15 framework, including its powerful App Router. It is optimized 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 localize 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.

    Note: Intlayer is compatible with Next.js 12, 13, 14, and 15. If you are using Next.js Page Router, 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
    1npm install intlayer next-intlayer
    bash
    1yarn add intlayer next-intlayer
    bash
    1pnpm add intlayer next-intlayer

    Step 2: Configure Your Project

    Create a config file to configure the languages of 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 // Your other locales 12 ], 13 defaultLocale: Locales.ENGLISH, 14 }, 15}; 16 17export default config;

    To see all available parameters, refer to the configuration documentation here.

    Step 3: Integrate Intlayer in Your Next.js Configuration

    Configure your Next.js setup to use Intlayer:

    typescript
    1// next.config.mjs 2import { withIntlayer } from "next-intlayer/server"; 3 4/** @type {import('next').NextConfig} */ 5const nextConfig = {}; 6 7export default withIntlayer(nextConfig);

    Step 4: Configure Middleware for Locale Detection

    Set up middleware to detect 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 for localized content:

    Change src/app/page.ts to src/app/[locale]/page.ts

    Then, implement the generateStaticParams function in your application Layout.

    tsx
    1// src/app/layout.tsx 2 3import type { ReactNode } from "react"; 4import "./globals.css"; 5 6export { generateStaticParams } from "next-intlayer"; // Line to insert 7 8const RootLayout = ({ 9 children, 10}: Readonly<{ 11 children: ReactNode; 12}>) => children; 13 14export default RootLayout;

    Then add a new layout in your [locale] directory:

    tsx
    1// src/app/[locale]/layout.tsx 2 3import { type NextLayoutIntlayer } from "next-intlayer"; 4import { Inter } from "next/font/google"; 5import { getHTMLTextDir } from "intlayer"; 6 7const inter = Inter({ subsets: ["latin"] }); 8 9const LocaleLayout: NextLayoutIntlayer = async ({ children, params }) => { 10 const { locale } = await params; 11 return ( 12 <html lang={locale} dir={getHTMLTextDir(locale)}> 13 <body className={inter.className}>{children}</body> 14 </html> 15 ); 16}; 17 18export default LocaleLayout;

    Step 6: Declare Your Content

    Create and manage your content dictionaries:

    tsx
    1// src/app/[locale]/page.content.ts 2import { t, type DeclarationContent } from "intlayer"; 3 4const pageContent = { 5 key: "page", 6 content: { 7 getStarted: { 8 main: t({ 9 en: "Get started by editing", 10 fr: "Commencez par éditer", 11 es: "Comience por editar", 12 }), 13 pageLink: "src/app/page.tsx", 14 }, 15 }, 16} satisfies DeclarationContent; 17 18export default pageContent;

    See how to declare your Intlayer declaration files.

    Step 7: Utilize Content in Your Code

    Access your content dictionaries throughout your application:

    tsx
    1// src/app/[locale]/page.ts 2 3import { ClientComponentExample } from "@component/ClientComponentExample"; 4import { LocaleSwitcher } from "@component/LangSwitcherDropDown"; 5import { NestedServerComponentExample } from "@component/NestedServerComponentExample"; 6import { ServerComponentExample } from "@component/ServerComponentExample"; 7import { type NextPageIntlayer, IntlayerClientProvider } from "next-intlayer"; 8import { IntlayerServerProvider, useIntlayer } from "next-intlayer/server"; 9 10const PageContent = () => { 11 const { title, content } = useIntlayer("page"); 12 13 return ( 14 <> 15 <p>{content.getStarted.main}</p> 16 <code>{content.getStarted.pageLink}</code> 17 </> 18 ); 19}; 20 21const Page: NextPageIntlayer = async ({ params }) => { 22 const { locale } = await params; 23 24 return ( 25 <> 26 {/** 27 * IntlayerServerProvider is used to provide the locale to the server children 28 * Doesn't work if set in the layout 29 */} 30 <IntlayerServerProvider locale={locale}> 31 <PageContent /> 32 <ServerComponentExample /> 33 </IntlayerServerProvider> 34 {/** 35 * IntlayerClientProvider is used to provide the locale to the client children 36 * Can be set in any parent component, including the layout 37 */} 38 <IntlayerClientProvider locale={locale}> 39 <ClientComponentExample /> 40 </IntlayerClientProvider> 41 </> 42 ); 43}; 44 45export default Page;
    tsx
    1// src/components/ClientComponentExample.tsx 2 3"use client"; 4 5import { useIntlayer } from "next-intlayer"; 6 7export const ClientComponentExample = () => { 8 const content = useIntlayer("client-component-example"); // Create related content declaration 9 10 return ( 11 <div> 12 <h2>{content.title} </h2> 13 <p>{content.content}</p> 14 </div> 15 ); 16};
    tsx
    1// src/components/ServerComponentExample.tsx 2 3import { useIntlayer } from "next-intlayer/server"; 4 5export const ServerComponentExample = () => { 6 const content = useIntlayer("server-component-example"); // Create related content declaration 7 8 return ( 9 <div> 10 <h2>{content.title} </h2> 11 <p>{content.content}</p> 12 </div> 13 ); 14};

    Note: 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:

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

    For more detailed usage of intlayer into Client, or Server component, see the Next.js example here.

    (Optional) Step 8: Internationalization of your metadata

    In the case you want to internationalize your metadata, such as the title of your page, you can use the generateMetadata function provided by Next.js. Inside the function use the getTranslationContent function to translate your metadata.

    typescript
    1// src/app/[locale]/layout.tsx or src/app/[locale]/page.tsx 2 3import { 4 type IConfigLocales, 5 getTranslationContent, 6 getMultilingualUrls, 7} from "intlayer"; 8import type { Metadata } from "next"; 9import type { LocalParams } from "next-intlayer"; 10 11export const generateMetadata = ({ 12 params: { locale }, 13}: LocalParams): Metadata => { 14 const t = <T>(content: IConfigLocales<T>) => 15 getTranslationContent(content, locale); 16 17 /** 18 * Generates an object containing all url for each locale. 19 * 20 * Example: 21 * ```ts 22 * getMultilingualUrls('/about'); 23 * 24 * // Returns 25 * // { 26 * // en: '/about', 27 * // fr: '/fr/about', 28 * // es: '/es/about', 29 * // } 30 * ``` 31 */ 32 const multilingualUrls = getMultilingualUrls("/"); 33 34 return { 35 title: t<string>({ 36 en: "My title", 37 fr: "Mon titre", 38 es: "Mi título", 39 }), 40 description: t({ 41 en: "My description", 42 fr: "Ma description", 43 es: "Mi descripción", 44 }), 45 alternates: { 46 canonical: url, 47 languages: { ...multilingualUrls, "x-default": "/" }, 48 }, 49 openGraph: { 50 url: multilingualUrls[locale], 51 }, 52 }; 53}; 54 55// ... Rest of the code

    Learn more about the metadata optimization on the official Next.js documentation.

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

    To internationalize 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.

    tsx
    1// src/app/sitemap.ts 2 3import { getMultilingualUrls } from "intlayer"; 4import type { MetadataRoute } from "next"; 5 6const sitemap = (): MetadataRoute.Sitemap => [ 7 { 8 url: "https://example.com", 9 alternates: { 10 languages: getMultilingualUrls("https://example.com"), 11 }, 12 }, 13 { 14 url: "https://example.com/login", 15 alternates: { 16 languages: getMultilingualUrls("https://example.com/login"), 17 }, 18 }, 19 { 20 url: "https://example.com/register", 21 alternates: { 22 languages: getMultilingualUrls("https://example.com/register"), 23 }, 24 }, 25]; 26 27export default sitemap;
    tsx
    1// src/app/robots.ts 2import type { MetadataRoute } from "next"; 3import { getMultilingualUrls } from "intlayer"; 4 5const getAllMultilingualUrls = (urls: string[]) => 6 urls.flatMap((url) => Object.values(getMultilingualUrls(url)) as string[]); 7 8const robots = (): MetadataRoute.Robots => ({ 9 rules: { 10 userAgent: "*", 11 allow: ["/"], 12 disallow: getAllMultilingualUrls(["/login", "/register"]), 13 }, 14 host: "https://example.com", 15 sitemap: `https://example.com/sitemap.xml`, 16}); 17 18export default robots;

    Learn more about the sitemap optimization on the official Next.js documentation. Learn more about the robots.txt optimization on the official Next.js documentation.

    (Optional) Step 10: 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.

    tsx
    1import { Locales } from "intlayer"; 2import { useLocale } from "next-intlayer"; 3 4const MyComponent = () => { 5 const { setLocale } = useLocale(); 6 7 return ( 8 <button onClick={() => setLocale(Locales.English)}>Change Language</button> 9 ); 10};

    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.

    json5
    1// tsconfig.json 2 3{ 4 // your custom config 5 include: [ 6 "src", 7 "types", // <- Include the auto generated types 8 ], 9}

    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
    1# Ignore the files generated by Intlayer 2.intlayer

    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