This project was created as I needed a custom i18n(internationalization) system in my Next.js projects and as a way to challenge myself to build a system like react-i18next.
Replace
<locale>
with your translations ISO639 set 1 locale name (en, fr, se ...) List of ISO 639 language codes - Wikipedia
Add new translation file as <locale>
.json to @/translations/
directory.Remember to match the translation key structure to other translation files.
Add <locale>
to translations in @/lib/i18n/loadTranslation.ts
.
const translations = {
en: () => import('@/translations/en.json').then((module) => module.default),
<locale>: () => import('@/translations/<locale>.json').then((module) => module.default),
...
};
<locale>
to i18nConfig.locales
array in @/i18n.ts
.export const i18nConfig = {
defaultLocale: 'en',
locales: ['en', '<locale>', ...],
}
The new translation files content should be available to be used now in your Next.js project.
When you render a component on the server side, you can simply call the getTranslation(locale: Locale)
function and get the needed translation. It's beneficial to keep the translations on the server side as the translation files are stored on the server. This also shortens the load on client as save on the runtime.
In @/app/[locale]page.tsx
...
type Props = {
params: {
locale: Locale;
};
};
export default async function ServerSidePage({ params: { locale } }: Props) {
const translation = await getTranslation(locale);
return (
<section>
<h1>
{translation('views.home.title')}
</h1>
<p>
{translation('views.home.body')}
</p>
</section>
);
}
It is recommended to keep translations on the server side but, translation values can be passed to client components from server components. For more information, look at how the following files pass the translation value to the locale-selector.tsx
client component from server components.
@/app/[locale]/page.tsx
@/components/nav.tsx
@/components/locale-selector.tsx