Internationalization (i18n)
Setup

Internationalization (i18n) with Full-Stack-Kit

Internationalization is the process of designing and preparing your app to be usable in different languages and regions. This is a key feature for any app that is intended to be used by a global audience. Full-Stack-Kit come with built-in support for internationalization. One more thing you don't have to worry about.

Setting Up i18n Configuration

  1. Open the i18n/config.ts file.

  2. Modify the i18n object to set your desired configurations:

export const i18n = {
  defaultLocale: "en",
  locales: ["en", "es", "fr"],
} as const;

Creating Language JSON Files

  1. In the /i18n folder, create separate JSON files for each language. Example: en.json, es.json, fr.json.

  2. Populate each JSON file with translated strings for the corresponding language.

Adding Languages to Dictionaries

  1. Open the i18n/dictionaries.ts file.

  2. Update the dictionaries object to include imports for each language JSON file:

export const dictionaries = {
  en: () => import("./en.json").then((module) => module.default),
  es: () => import("./es.json").then((module) => module.default),
  fr: () => import("./fr.json").then((module) => module.default),
};

Usage in Server Components

  1. In server components, import getI18n to access the translation function.

  2. Inside your component, use getI18n to get the translation function.

import { getI18n } from "@/i18n/get-i18n";
 
export default async function Home({ params: { locale } }: Props) {
  const { t } = await getI18n(locale);
 
  return (
    <>
      <h1>{t("landing.welcome")}</h1>
    </>
  );
}

Usage in Client Components

  1. In client components, import useI18n to access the translation function.

  2. Inside your component, use useI18n to get the translation function.

import { useI18n } from "@/i18n/context";
 
export default function Pricing() {
  const { t } = useI18n();
 
  return (
    <div>
      <h2>{t("pricing.title")}</h2>
      <p>{t("pricing.description")}</p>
    </div>
  );
}

Passing Variables to Translations

  1. In your JSON file, use curly braces to define variable placeholders:
{
  "dashboard": {
    "greeting": "Hello {userName}, welcome back!"
  }
}
  1. Inside your component, pass variables to the translation function:
export default function Dashboard() {
  const { t } = useI18n();
 
  return (
    <section className="relative overflow-hidden">
      <h2>{t("dashboard.greeting", { userName: "John" })}</h2>
    </section>
  );
}

Additional Notes

  • Ensure all translations are accurately provided in the language-specific JSON files.
  • Variables passed to translations should match the placeholders defined in the JSON files.

Conclusion

Full-Stack-Kit makes it easy to add internationalization to your app. We built everything you need to get started, so you can focus on creating a great user experience for your global audience.

Full-Stack-Kit © 2024