See Application Template on GitHub.
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.
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.
Install the necessary packages using npm:
npm install intlayer next-intlayer
pnpm add intlayer next-intlayer
yarn add 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.
Create a config file to configure the languages of your application:
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;
import { Locales } from "intlayer";
/** @type {import('intlayer').IntlayerConfig} */
const config = {
internationalization: {
locales: [
Locales.ENGLISH,
Locales.FRENCH,
Locales.SPANISH,
// Your other locales
],
defaultLocale: Locales.ENGLISH,
},
};
export default config;
const { Locales } = require("intlayer");
/** @type {import('intlayer').IntlayerConfig} */
const config = {
internationalization: {
locales: [
Locales.ENGLISH,
Locales.FRENCH,
Locales.SPANISH,
// Your other locales
],
defaultLocale: Locales.ENGLISH,
},
};
module.exports = 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.
Configure your Next.js setup to use Intlayer:
import type { NextConfig } from "next";
import { withIntlayer } from "next-intlayer/server";
const nextConfig: NextConfig = {
/* config options here */
};
export default withIntlayer(nextConfig);
import { withIntlayer } from "next-intlayer/server";
/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
};
export default withIntlayer(nextConfig);
const { withIntlayer } = require("next-intlayer/server");
/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
};
module.exports = 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.
Remove everything from RootLayout
and replace it with the following code:
import type { PropsWithChildren, FC } from "react";
import "./globals.css";
const RootLayout: FC<PropsWithChildren> = ({ children }) => children;
export default RootLayout;
import "./globals.css";
const RootLayout = ({ children }) => children;
export default RootLayout;
require("./globals.css");
const RootLayout = ({ children }) => children;
module.exports = {
default: RootLayout,
generateStaticParams,
};
Keeping the
RootLayout
component empty allows to set thelang
anddir
attributes to the<html>
tag.
To implement dynamic routing, provide the path for the locale by adding a new layout in your [locale]
directory:
import type { NextLayoutIntlayer } 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}>{children}</body>
</html>
);
};
export default LocaleLayout;
import { getHTMLTextDir } from "intlayer";
const inter = Inter({ subsets: ["latin"] });
const LocaleLayout = async ({ children, params: { locale } }) => {
const { locale } = await params;
return (
<html lang={locale} dir={getHTMLTextDir(locale)}>
<body className={inter.className}>{children}</body>
</html>
);
};
export default LocaleLayout;
const { Inter } = require("next/font/google");
const { getHTMLTextDir } = require("intlayer");
const inter = Inter({ subsets: ["latin"] });
const LocaleLayout = async ({ children, params: { locale } }) => {
const { locale } = await params;
return (
<html lang={locale} dir={getHTMLTextDir(locale)}>
<body className={inter.className}>{children}</body>
</html>
);
};
module.exports = LocaleLayout;
The
[locale]
path segment is used to define the locale. Example:/en-US/about
will refer toen-US
and/fr/about
tofr
.
Then, implement the generateStaticParams
function in your application Layout.
export { generateStaticParams } from "next-intlayer"; // Line to insert
const LocaleLayout: NextLayoutIntlayer = async ({ children, params }) => {
/*... Rest of the code*/
};
export default LocaleLayout;
export { generateStaticParams } from "next-intlayer"; // Line to insert
const LocaleLayout = async ({ children, params: { locale } }) => {
/*... Rest of the code*/
};
// ... Rest of the code
const { generateStaticParams } = require("next-intlayer"); // Line to insert
const LocaleLayout = async ({ children, params: { locale } }) => {
/*... Rest of the code*/
};
module.exports = { default: LocaleLayout, generateStaticParams };
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.
Create and manage your content declarations to store translations:
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;
import { t } from "intlayer";
/** @type {import('intlayer').Dictionary} */
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",
},
},
};
export default pageContent;
const { t } = require("intlayer");
/** @type {import('intlayer').Dictionary} */
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",
},
},
};
module.exports = pageContent;
{
"$schema": "https://intlayer.org/schema.json",
"key": "page",
"content": {
"getStarted": {
"nodeType": "translation",
"translation": {
"en": "Get started by editing",
"fr": "Commencez par éditer",
"es": "Comience por editar"
}
},
"pageLink": {
"nodeType": "translation",
"translation": {
"en": "src/app/page.tsx",
"fr": "src/app/page.tsx",
"es": "src/app/page.tsx"
}
}
}
}
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,mjx,cjs,cjx}
). For more details, refer to the content declaration documentation.
Access your content dictionaries throughout your application:
import type { FC } from "react";
import { ClientComponentExample } from "@components/ClientComponentExample";
import { ServerComponentExample } from "@components/ServerComponentExample";
import { type NextPageIntlayer, IntlayerClientProvider } 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 />
<IntlayerClientProvider locale={locale}>
<ClientComponentExample />
</IntlayerClientProvider>
</IntlayerServerProvider>
);
};
export default Page;
import { ClientComponentExample } from "@components/ClientComponentExample";
import { ServerComponentExample } from "@components/ServerComponentExample";
import { IntlayerClientProvider } from "next-intlayer";
import { IntlayerServerProvider, useIntlayer } from "next-intlayer/server";
const PageContent = () => {
const content = useIntlayer("page");
return (
<>
<p>{content.getStarted.main}</p>
<code>{content.getStarted.pageLink}</code>
</>
);
};
const Page = async ({ params }) => {
const { locale } = await params;
return (
<IntlayerServerProvider locale={locale}>
<PageContent />
<ServerComponentExample />
<IntlayerClientProvider locale={locale}>
<ClientComponentExample />
</IntlayerClientProvider>
</IntlayerServerProvider>
);
};
export default Page;
import { ClientComponentExample } from "@components/ClientComponentExample";
import { ServerComponentExample } from "@components/ServerComponentExample";
import { IntlayerClientProvider } from "next-intlayer";
import { IntlayerServerProvider, useIntlayer } from "next-intlayer/server";
const PageContent = () => {
const content = useIntlayer("page");
return (
<>
<p>{content.getStarted.main}</p>
<code>{content.getStarted.pageLink}</code>
</>
);
};
const Page = async ({ params }) => {
const { locale } = await params;
return (
<IntlayerServerProvider locale={locale}>
<PageContent />
<ServerComponentExample />
<IntlayerClientProvider locale={locale}>
<ClientComponentExample />
</IntlayerClientProvider>
</IntlayerServerProvider>
);
};
-
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 usingIntlayerClientProvider
in the layout, you avoid reinitializing it for every page, improving performance and maintaining a consistent localization 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.
"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>
);
};
"use client";
import { useIntlayer } from "next-intlayer";
const ClientComponentExample = () => {
const content = useIntlayer("client-component-example"); // Create related content declaration
return (
<div>
<h2>{content.title} </h2>
<p>{content.content}</p>
</div>
);
};
"use client";
const { useIntlayer } = require("next-intlayer");
const ClientComponentExample = () => {
const content = useIntlayer("client-component-example"); // Create related content declaration
return (
<div>
<h2>{content.title} </h2>
<p>{content.content}</p>
</div>
);
};
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>
);
};
import { useIntlayer } from "next-intlayer/server";
const ServerComponentExample = () => {
const content = useIntlayer("server-component-example"); // Create related content declaration
return (
<div>
<h2>{content.title} </h2>
<p>{content.content}</p>
</div>
);
};
const { useIntlayer } = require("next-intlayer/server");
const ServerComponentExample = () => {
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 asalt
,title
,href
,aria-label
, etc., you must call the value of the function, like:<img src={content.image.src.value} alt={content.image.value} />
To Learn more about the
useIntlayer
hook, refer to the documentation.
Set up middleware to detect the user's preferred locale:
export { intlayerMiddleware as middleware } from "next-intlayer/middleware";
export const config = {
matcher:
"/((?!api|static|assets|robots|sitemap|sw|service-worker|manifest|.*\\..*|_next).*)",
};
export { intlayerMiddleware as middleware } from "next-intlayer/middleware";
export const config = {
matcher:
"/((?!api|static|assets|robots|sitemap|sw|service-worker|manifest|.*\\..*|_next).*)",
};
const { intlayerMiddleware } = require("next-intlayer/middleware");
const config = {
matcher:
"/((?!api|static|assets|robots|sitemap|sw|service-worker|manifest|.*\\..*|_next).*)",
};
module.exports = { middleware: intlayerMiddleware, config };
The
intlayerMiddleware
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.
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 getTranslation
function to translate your metadata.
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);
/**
* 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("/");
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",
}),
alternates: {
canonical: multilingualUrls[locale as keyof typeof multilingualUrls],
languages: { ...multilingualUrls, "x-default": "/" },
},
openGraph: {
url: multilingualUrls[locale],
},
};
};
// ... Rest of the code
import { getTranslation, getMultilingualUrls } from "intlayer";
export const generateMetadata = async ({ params }) => {
const { locale } = await params;
const t = (content) => getTranslation(content, 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("/");
return {
title: t({
en: "My title",
fr: "Mon titre",
es: "Mi título",
}),
description: t({
en: "My description",
fr: "Ma description",
es: "Mi descripción",
}),
alternates: {
canonical: multilingualUrls[locale],
languages: { ...multilingualUrls, "x-default": "/" },
},
openGraph: {
url: multilingualUrls[locale],
},
};
};
// ... Rest of the code
const { getTranslation, getMultilingualUrls } = require("intlayer");
const generateMetadata = async ({ params }) => {
const { locale } = await params;
const t = (content) => getTranslation(content, 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("/");
return {
title: t({
en: "My title",
fr: "Mon titre",
es: "Mi título",
}),
description: t({
en: "My description",
fr: "Ma description",
es: "Mi descripción",
}),
alternates: {
canonical: multilingualUrls[locale],
languages: { ...multilingualUrls, "x-default": "/" },
},
openGraph: {
url: multilingualUrls[locale],
},
};
};
module.exports = { generateMetadata };
// ... Rest of the code
Learn more about the metadata optimization on the official Next.js documentation.
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.
import { getMultilingualUrls } from "intlayer";
import type { MetadataRoute } from "next";
const sitemap = (): MetadataRoute.Sitemap => [
{
url: "https://example.com",
alternates: {
languages: { ...getMultilingualUrls("https://example.com") },
},
},
{
url: "https://example.com/login",
alternates: {
languages: { ...getMultilingualUrls("https://example.com/login") },
},
},
{
url: "https://example.com/register",
alternates: {
languages: { ...getMultilingualUrls("https://example.com/register") },
},
},
];
export default sitemap;
import { getMultilingualUrls } from "intlayer";
const sitemap = () => [
{
url: "https://example.com",
alternates: {
languages: { ...getMultilingualUrls("https://example.com") },
},
},
{
url: "https://example.com/login",
alternates: {
languages: { ...getMultilingualUrls("https://example.com/login") },
},
},
{
url: "https://example.com/register",
alternates: {
languages: { ...getMultilingualUrls("https://example.com/register") },
},
},
];
export default sitemap;
const { getMultilingualUrls } = require("intlayer");
const sitemap = () => [
{
url: "https://example.com",
alternates: {
languages: { ...getMultilingualUrls("https://example.com") },
},
},
{
url: "https://example.com/login",
alternates: {
languages: { ...getMultilingualUrls("https://example.com/login") },
},
},
{
url: "https://example.com/register",
alternates: {
languages: { ...getMultilingualUrls("https://example.com/register") },
},
},
];
module.exports = sitemap;
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;
import { getMultilingualUrls } from "intlayer";
const getAllMultilingualUrls = (urls) =>
urls.flatMap((url) => Object.values(getMultilingualUrls(url)));
const robots = () => ({
rules: {
userAgent: "*",
allow: ["/"],
disallow: getAllMultilingualUrls(["/login", "/register"]),
},
host: "https://example.com",
sitemap: `https://example.com/sitemap.xml`,
});
export default robots;
const { getMultilingualUrls } = require("intlayer");
const getAllMultilingualUrls = (urls) =>
urls.flatMap((url) => Object.values(getMultilingualUrls(url)));
const robots = () => ({
rules: {
userAgent: "*",
allow: ["/"],
disallow: getAllMultilingualUrls(["/login", "/register"]),
},
host: "https://example.com",
sitemap: `https://example.com/sitemap.xml`,
});
module.exports = 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.
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.
"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)}
hrefLang={localeItem}
key={localeItem}
aria-current={locale === localeItem ? "page" : undefined}
onClick={(e) => {
e.preventDefault();
setLocale(localeItem);
}}
>
<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>
);
};
"use client";
import {
Locales,
getHTMLTextDir,
getLocaleName,
getLocalizedUrl,
} from "intlayer";
import { useLocale } from "next-intlayer";
import Link from "next/link";
export const LocaleSwitcher = () => {
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)}
hrefLang={localeItem}
key={localeItem}
aria-current={locale === localeItem ? "page" : undefined}
onClick={(e) => {
e.preventDefault();
setLocale(localeItem);
}}
>
<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>
);
};
"use client";
const {
Locales,
getHTMLTextDir,
getLocaleName,
getLocalizedUrl,
} = require("intlayer");
const { useLocale } = require("next-intlayer");
const Link = require("next/link");
export const LocaleSwitcher = () => {
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)}
hrefLang={localeItem}
key={localeItem}
aria-current={locale === localeItem ? "page" : undefined}
onClick={(e) => {
e.preventDefault();
setLocale(localeItem);
}}
>
<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>
);
};
Documentation references:
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, so that. 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 behavior is useful for several reasons:
- SEO and User Experience: Localized URLs help search engines index language-specific pages correctly and provide users with content in their preferred language.
- Consistency: By using a localized link throughout your application, you guarantee that navigation stays within the current locale, preventing unexpected language switches.
- Maintainability: Centralizing the localization 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 localized Link
component in TypeScript:
"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 localized URL.
const hrefI18n: NextLinkProps["href"] =
href && !isExternalLink ? getLocalizedUrl(href.toString(), locale) : href;
return (
<NextLink href={hrefI18n} {...props}>
{children}
</NextLink>
);
};
"use client";
import { getLocalizedUrl } from "intlayer";
import NextLink from "next/link";
import { useLocale } from "next-intlayer";
/**
* 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) => /^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 = ({ href, children, ...props }) => {
const { locale } = useLocale();
const isExternalLink = checkIsExternalLink(href.toString());
// If the link is internal and a valid href is provided, get the localized URL.
const hrefI18n =
href && !isExternalLink ? getLocalizedUrl(href.toString(), locale) : href;
return (
<NextLink href={hrefI18n} {...props}>
{children}
</NextLink>
);
};
"use client";
const { getLocalizedUrl } = require("intlayer");
const NextLink = require("next/link");
const { useLocale } = require("next-intlayer");
/**
* Utility function to check whether a given URL is external.
* If the URL starts with http:// or https://, it's considered external.
*/
const checkIsExternalLink = (href) => /^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.
*/
const Link = ({ href, children, ...props }) => {
const { locale } = useLocale();
const isExternalLink = checkIsExternalLink(href.toString());
// If the link is internal and a valid href is provided, get the localized URL.
const hrefI18n =
href && !isExternalLink ? getLocalizedUrl(href.toString(), locale) : href;
return (
<NextLink href={hrefI18n} {...props}>
{children}
</NextLink>
);
};
-
Detecting External Links:
The helper functioncheckIsExternalLink
determines whether a URL is external. External links are left unchanged because they do not need localization. -
Retrieving the Current Locale:
TheuseLocale
hook provides the current locale (e.g.,fr
for French). -
Localizing 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 thehref
will transform it to/fr/about
. -
Returning the Link:
The component returns an<a>
element with the localized 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.
Intlayer use module augmentation to get benefits of TypeScript and make your codebase stronger.
Ensure your TypeScript configuration includes the autogenerated types.
{
// ... Your existing TypeScript configurations
"include": [
// ... Your existing TypeScript configurations
".intlayer/**/*.ts", // Include the auto-generated types
],
}
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:
# Ignore the files generated by Intlayer
.intlayer
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.
To go further, you can implement the visual editor or externalize your content using the CMS.