Next js

Internationalization (i18n) In Next Js


What is i18n?

  • Internationalization means designing your app to support multiple languages and locales.

  • Makes your app accessible to a global audience.


1. Built-in i18n Support in Next.js

Next.js has native support for internationalized routing since version 10.

You configure it in your next.config.js:

js
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'], // Supported languages
defaultLocale: 'en', // Default language
},
};

2. How It Works

  • Next.js automatically prefixes routes with locale (e.g., /fr/about).

  • It provides locale, locales, and defaultLocale in useRouter() for language detection.

  • Automatic routing and redirects based on user’s language preferences.


3. Handling Translations


a) Static Translations with JSON Files

Store translations in JSON files, e.g.:

bash
/locales/en/common.json
/locales/fr/common.json

b) Using a Library — next-i18next

  • Popular and easy-to-use.

  • Manages translation loading, namespaces, and language switching.

Setup example:

  1. Install:

bash
npm install next-i18next react-i18next i18next
  1. Create next-i18next.config.js:

js
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr', 'de'],
},
};
  1. Configure _app.js:

jsx
import { appWithTranslation } from 'next-i18next';

function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}

export default appWithTranslation(MyApp);

  1. Use in components:

jsx
import { useTranslation } from 'next-i18next';

export default function Home() {
const { t } = useTranslation('common');
return <h1>{t('welcome')}</h1>;
}


4. Detecting User Language

  • Next.js can detect language from headers or cookies.

  • You can also provide a language switcher UI for manual change.


5. SEO Benefits

  • Locale-specific URLs help search engines index your content properly.

  • Use <link rel="alternate" hreflang="..."> tags to indicate language versions.


Summary Table

Feature Description
Locale routing Automatic locale prefixes in URLs
Translation handling JSON files or libraries like next-i18next
Language detection Based on browser headers, cookies, or user input
SEO support hreflang tags, localized URLs

Leave a Reply

Your email address will not be published. Required fields are marked *