Introduction
Localization (l10n) allows your application to support multiple languages. This guide shows how to set up localization in Next.js using next-i18next.
1. Setup
1.1 Install Dependencies
Install next-i18next, i18next, and react-i18next.
npm install next-i18next i18next react-i18next
1.2 Configure next-i18next
Create next-i18next.config.js.
// next-i18next.config.js
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr', 'es'],
},
};
Update next.config.js.
// next.config.js
const { i18n } = require('./next-i18next.config');
module.exports = { i18n };
2. Translation Files
2.1 Create Translation Files
Organize translation files under public/locales.
public/
locales/
en/
common.json
fr/
common.json
es/
common.json
Example content for common.json.
// public/locales/en/common.json
{
"welcome": "Welcome",
"goodbye": "Goodbye"
}
3. Using Translations
3.1 Configure _app.js
Wrap your app with appWithTranslation.
// pages/_app.js
import { appWithTranslation } from 'next-i18next';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default appWithTranslation(MyApp);
3.2 Using useTranslation Hook
Access translations in components.
// components/Hello.js
import { useTranslation } from 'next-i18next';
const Hello = () => {
const { t } = useTranslation('common');
return <h1>{t('welcome')}</h1>;
};
export default Hello;
3.3 Server-Side and Static Props
For server-side or static generation.
// pages/index.js
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import Hello from '../components/Hello';
const Home = () => <Hello />;
export async function getServerSideProps(context) {
return {
props: {
...(await serverSideTranslations(context.locale, ['common'])),
},
};
}
export default Home;
4. Locale Switching
4.1 Add Locale Switcher
Create a locale switcher component.
// components/LocaleSwitcher.js
import { useRouter } from 'next/router';
import { setCookie } from 'nookies';
const LocaleSwitcher = () => {
const { locale, locales, push } = useRouter();
const handleLocaleChange = (lng) => {
setCookie(null, 'NEXT_LOCALE', lng, { path: '/' });
push('/', '/', { locale: lng });
};
return (
<div>
{locales.map((lng) => (
<button
key={lng}
onClick={() => handleLocaleChange(lng)}
style={{ fontWeight: locale === lng ? 'bold' : 'normal' }}
>
{lng}
</button>
))}
</div>
);
};
export default LocaleSwitcher;
5. Testing Localization
5.1 Verify Translations and Switching
Ensure translations are displayed correctly and the locale switcher functions properly.
Summary
Integrating localization in Next.js using next-i18next enables multi-language support. Follow these steps to set up, use, and manage translations effectively in your application.