next-i18n-boilerplate
v1.1.2
Published
A complete localization solution for Next.js 15+ without external packages. Supports server-side rendering, client-side translations, and efficient language switching.
Maintainers
Readme
next-i18n-boilerplate
A complete localization solution for Next.js 15+ without external packages. Supports server-side rendering, client-side translations, and efficient language switching.
🌟 Features
- ✅ Server-side translations for pages (SEO friendly)
- ✅ Client-side translations for interactive components
- ✅ No middleware required - pure client-side navigation
- ✅ Immediate cookie updates with language preference persistence
- ✅ RTL support for Arabic language
- ✅ TypeScript support with proper typing
- ✅ Efficient page reloads for consistent state
- ✅ Smart language switcher - hides current language
- ✅ Fully configurable - users can set their own locales and languages
- ✅ Helper functions for creating custom configurations
📦 Installation
npm install next-i18n-boilerplate
# or
yarn add next-i18n-boilerplate
# or
pnpm add next-i18n-boilerplate🚀 Quick Start
1. Setup Locale Configuration
Create your locale configuration with your desired languages:
// src/lib/i18n/config.ts
import { createLocaleConfig } from "next-i18n-boilerplate";
// Configure your own locales and default language
export const { LOCALES, DEFAULT_LOCALE } = createLocaleConfig(
["en", "ar", "fr", "de", "es"] as const, // Add any languages you want
"en" // Set your default language
);
export type Locale = (typeof LOCALES)[number];2. Create Translation Files
// src/locales/en.json
{
"home.title": "Welcome",
"about.title": "About Us",
"hello.title": "Hello World"
}
// src/locales/ar.json
{
"home.title": "مرحبا",
"about.title": "معلومات عنا",
"hello.title": "مرحبا بالعالم"
}
// src/locales/fr.json
{
"home.title": "Bienvenue",
"about.title": "À propos",
"hello.title": "Bonjour le monde"
}3. Setup App Router Structure
// src/app/[locale]/layout.tsx
import { getDictionary } from "next-i18n-boilerplate";
export default async function LocaleLayout({
children,
params,
}: {
children: React.ReactNode;
params: { locale: string };
}) {
const { locale } = await params;
const dict = await getDictionary(locale);
return (
<html lang={locale} dir={locale === "ar" ? "rtl" : "ltr"}>
<body>
{children}
</body>
</html>
);
}4. Use Server-Side Translations
// src/app/[locale]/page.tsx
import { getDictionary } from "next-i18n-boilerplate";
export default async function Home({ params }: { params: { locale: string } }) {
const { locale } = await params;
const dict = await getDictionary(locale);
return <h1>{dict["home.title"]}</h1>;
}5. Use Client-Side Translations
// src/components/MyComponent.tsx
"use client";
import { useLocale } from "next-i18n-boilerplate";
export default function MyComponent() {
const { t, locale } = useLocale();
return (
<div>
<h2>{t("myComponent.title")}</h2>
<p>Current locale: {locale}</p>
</div>
);
}6. Add Language Switcher
// src/components/Header.tsx
"use client";
import React from "react";
import { LanguageSwitcher } from "next-i18n-boilerplate/components"; // adjust path if needed
import { createSetClientLocale } from "next-i18n-boilerplate/client";
const locales = ["en", "ar", "fr", "de", "es"] as const;
const labels = {
en: "English",
ar: "العربية",
fr: "Français",
de: "Deutsch",
es: "Español"
};
export default function Header() {
// if you have a client locale setter
const setClientLocale = createSetClientLocale(locales, "en");
return (
<header className="p-4 bg-gray-800 text-white flex justify-between items-center">
<h1>My App</h1>
<LanguageSwitcher
locales={locales} // supported locales
localeLabels={labels} // optional labels
setClientLocale={setClientLocale} // optional function to update cookie / state
/>
</header>
);
}
🔧 Advanced Configuration
Custom Locale Configuration
You can create completely custom configurations:
// src/lib/i18n/config.ts
import { createLocaleConfig } from "next-i18n-boilerplate";
// Define your locales with custom types
const myLocales = ["en", "ar", "fr", "de", "es", "ja", "ko"] as const;
export const { LOCALES, DEFAULT_LOCALE } = createLocaleConfig(myLocales, "en");
export type Locale = (typeof LOCALES)[number];
// You can also add custom locale metadata
export const LOCALE_METADATA = {
en: { name: "English", flag: "🇺🇸", rtl: false },
ar: { name: "العربية", flag: "🇸🇦", rtl: true },
fr: { name: "Français", flag: "🇫🇷", rtl: false },
de: { name: "Deutsch", flag: "🇩🇪", rtl: false },
es: { name: "Español", flag: "🇪🇸", rtl: false },
ja: { name: "日本語", flag: "🇯🇵", rtl: false },
ko: { name: "한국어", flag: "🇰🇷", rtl: false }
} as const;Custom Translation Functions
Create your own translation functions with custom dictionaries:
// src/lib/i18n/myTranslations.ts
import { createGetDictionary } from "next-i18n-boilerplate";
// Import your translation files
import en from "@/locales/en.json";
import ar from "@/locales/ar.json";
import fr from "@/locales/fr.json";
const myDictionaries = { en, ar, fr };
// Create your own getDictionary function
export const getDictionary = createGetDictionary(myDictionaries);Custom Hooks
Create custom hooks for your specific needs:
// src/lib/i18n/myHooks.ts
import { createUseLocale } from "next-i18n-boilerplate";
// Import your translation files
import en from "@/locales/en.json";
import ar from "@/locales/ar.json";
import fr from "@/locales/fr.json";
const myDictionaries = { en, ar, fr };
const myLocales = ["en", "ar", "fr"] as const;
// Create your own useLocale hook
export const useLocale = createUseLocale(myDictionaries, myLocales, "en");Custom Components
Create custom components with your locale configuration:
// src/components/Header.tsx
import { createLanguageSwitcher } from "next-i18n-boilerplate";
const myLocales = ["en", "ar", "fr", "de"] as const;
const myLabels = {
en: "English",
ar: "العربية",
fr: "Français",
de: "Deutsch"
};
export const MyLanguageSwitcher = createLanguageSwitcher(myLocales, myLabels);// src/components/Header.tsx
import { LocalizedLink } from "next-i18n-boilerplate/components";
<LocalizedLink href="/contact" className="hover:text-gray-300">
<span>Contact us</span>
</LocalizedLink>📚 API Reference
Core Functions
getDictionary(locale: string, customDictionaries?)
Server-side function to get translations for a specific locale.
import { getDictionary } from "next-i18n-boilerplate";
const dict = await getDictionary("en");
console.log(dict["home.title"]); // "Welcome"createGetDictionary(dictionaries)
Helper function to create custom getDictionary functions.
import { createGetDictionary } from "next-i18n-boilerplate";
const myDictionaries = { en: enDict, ar: arDict, fr: frDict };
export const getDictionary = createGetDictionary(myDictionaries);useLocale()
React hook for client-side components to access current locale and translations.
import { useLocale } from "next-i18n-boilerplate";
function MyComponent() {
const { t, locale } = useLocale();
return (
<div>
<h1>{t("title")}</h1>
<p>Current locale: {locale}</p>
</div>
);
}createUseLocale(dictionaries, locales, defaultLocale)
Helper function to create custom useLocale hooks.
import { createUseLocale } from "next-i18n-boilerplate";
const myDictionaries = { en: enDict, ar: arDict, fr: frDict };
const myLocales = ["en", "ar", "fr"] as const;
export const useLocale = createUseLocale(myDictionaries, myLocales, "en");Components
LanguageSwitcher
Smart language switcher component that automatically hides the current language.
import { LanguageSwitcher } from "next-i18n-boilerplate";
<LanguageSwitcher />createLanguageSwitcher(locales, localeLabels?)
Helper function to create custom language switchers.
import { createLanguageSwitcher } from "next-i18n-boilerplate";
const myLocales = ["en", "ar", "fr"] as const;
const myLabels = { en: "English", ar: "العربية", fr: "Français" };
export const LanguageSwitcher = createLanguageSwitcher(myLocales, myLabels);LocalizedLink
Locale-aware navigation link component.
import { LocalizedLink } from "next-i18n-boilerplate";
<LocalizedLink href="/about">About</LocalizedLink>createLocalizedLink(locales)
Helper function to create custom localized link components.
import { createLocalizedLink } from "next-i18n-boilerplate";
const myLocales = ["en", "ar", "fr"] as const;
export const LocalizedLink = createLocalizedLink(myLocales);Utilities
setClientLocale(locale: string)
Set the client-side locale and update cookies.
import { setClientLocale } from "next-i18n-boilerplate";
setClientLocale("ar");createLocaleConfig(locales, defaultLocale)
Helper function to create locale configurations.
import { createLocaleConfig } from "next-i18n-boilerplate";
export const { LOCALES, DEFAULT_LOCALE } = createLocaleConfig(
["en", "ar", "fr", "de"] as const,
"en"
);🌐 Adding New Languages
- Add locale to your config:
export const { LOCALES, DEFAULT_LOCALE } = createLocaleConfig(
["en", "ar", "fr", "de", "es", "ja"] as const, // Added Japanese
"en"
);- Create translation file:
// src/locales/ja.json
{
"home.title": "ようこそ",
"about.title": "私たちについて",
"hello.title": "こんにちは世界"
}- Update your custom components (if using create functions):
// The create functions automatically handle new locales
// No manual updates needed!🔧 Configuration Options
Custom Locale Detection
You can customize how locales are detected by modifying the utility functions:
// Custom locale detection logic
function getLocaleFromPath(pathname: string): Locale {
const pathLocale = pathname.split('/')[1];
if (LOCALES.includes(pathLocale as Locale)) {
return pathLocale as Locale;
}
return DEFAULT_LOCALE;
}RTL Support
The package automatically handles RTL for Arabic and other RTL languages:
// In your layout
<html lang={locale} dir={locale === "ar" ? "rtl" : "ltr"}>Custom Locale Metadata
You can add custom metadata for each locale:
export const LOCALE_METADATA = {
en: { name: "English", flag: "🇺🇸", rtl: false, currency: "USD" },
ar: { name: "العربية", flag: "🇸🇦", rtl: true, currency: "SAR" },
fr: { name: "Français", flag: "🇫🇷", rtl: false, currency: "EUR" }
} as const;🧪 Testing
Server-Side Translations
# Test English
curl http://localhost:3000/en | grep "Welcome"
# Test Arabic
curl http://localhost:3000/ar | grep "مرحبا"
# Test French
curl http://localhost:3000/fr | grep "Bienvenue"Client-Side Translations
- Visit any page with client components
- Switch languages using the language switcher
- Verify both server and client translations update
🔍 Key Benefits
- 🎯 SEO Optimized: Server-side rendered content
- ⚡ Performance: No client-side translation loading
- 🔄 Real-time: Client components update instantly
- 🧹 Clean Code: No middleware complexity
- 📱 Responsive: Works on all devices
- 🔧 Maintainable: Clear separation of concerns
- 🌍 Scalable: Easy to add new languages
- ⚙️ Configurable: Users can set their own locales and languages
- 🔨 Flexible: Helper functions for custom configurations
🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
📄 License
MIT License - feel free to use this package in your projects!
