Setting up internationalization (i18n) in Next.js involves several key steps. Next.js has included built-in internationalization routing support starting from version 10. I'll walk you through the steps to set it up:
Step 1: Configure next.config.js
First, configure the i18n property in the next.config.js file. Here, define your default language (locale), supported languages, and domain mappings.
javascriptmodule.exports = { i18n: { locales: ['en-US', 'fr', 'es'], defaultLocale: 'en-US', // Optional: for domain-based internationalization domains: [ { domain: 'example.com', defaultLocale: 'en-US', }, { domain: 'example.fr', defaultLocale: 'fr', }, { domain: 'example.es', defaultLocale: 'es', }, ], }, }
Step 2: Use next-translate or other libraries
While Next.js provides built-in internationalization routing, it does not handle text translation. Use libraries like next-translate to manage text translation. First, install next-translate:
bashnpm install next-translate
Then, create an i18n.js configuration file to specify translation file paths and supported languages:
javascriptmodule.exports = { locales: ['en-US', 'fr', 'es'], defaultLocale: 'en-US', pages: { '*': ['common'], '/about': ['about'], }, loadLocaleFrom: (lang, ns) => import(`./locales/${lang}/${ns}.json`).then(m => m.default), }
Step 3: Use Translation in Pages
Within your page components, utilize the useTranslation hook to access the translation function and apply it to translate text.
javascriptimport useTranslation from 'next-translate/useTranslation' export default function HomePage() { const { t, lang } = useTranslation('common') return <h1>{t('welcome')}</h1> }
Step 4: Deployment and Testing
Deploy your application and verify all configurations are correct. Access your site via different domains or paths to ensure it displays the appropriate language.
By following these steps, you can implement multilingual support in your Next.js project, providing a more localized user experience.