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.
- Translation system based on a .json files.
- Dynamic auto-completion generation for the translation keys improving DX.
- Automatic user locale detection.
- Server side rendering.
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),
...
};
- Add the new
<locale>
toi18nConfig.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.
- Server:
@/app/[locale]/page.tsx
- Server:
@/components/nav.tsx
- Client:
@/components/locale-selector.tsx