Dynamic locale routing is a crucial feature for internationalizing web applications, allowing users to switch between different languages seamlessly. In this tutorial, we will explore how to implement dynamic locale routing in a Next.js application using the next-i18next library.
Before diving into the implementation, ensure you have the following:
First, create a new Next.js project if you haven't already:
npx create-next-app@latest my-i18n-app
cd my-i18n-app
Next, install the necessary packages for internationalization:
npm install next-i18next i18next react-i18next
next-i18nextCreate a configuration file for next-i18next in your project root directory named next-i18next.config.js:
// next-i18next.config.js
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
},
};
This configuration sets the default locale to English (en) and supports French (fr). You can add more languages as needed.
Create a directory named public/locales in your project root. Inside this directory, create subdirectories for each language you want to support:
mkdir -p public/locales/en
mkdir -p public/locales/fr
Next, create translation files for each language. For example, create common.json inside both en and fr directories:
public/locales/en/common.json
{
"welcome": "Welcome to our site!",
"greeting": "Hello, {{name}}!"
}
public/locales/fr/common.json
{
"welcome": "Bienvenue sur notre site!",
"greeting": "Bonjour, {{name}}!"
}
next-i18next in Your ApplicationCreate a file named _app.js inside the pages directory to initialize next-i18next:
// pages/_app.js
import { appWithTranslation } from 'next-i18next';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default appWithTranslation(MyApp);
To implement dynamic locale routing, you need to create a custom server or use Next.js's built-in support for locale detection. Here, we'll use the built-in support.
Next.js automatically detects the locale from the URL path. To ensure that your application supports this, update your next.config.js file:
// next.config.js
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
},
};
Create a component to allow users to switch between locales. This component will use the useRouter hook from Next.js and the useTranslation hook from react-i18next.
components/LocaleSwitcher.js
// components/LocaleSwitcher.js
import { useRouter } from 'next/router';
import { useTranslation } from 'react-i18next';
const LocaleSwitcher = () => {
const router = useRouter();
const { i18n } = useTranslation();
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
router.push(router.pathname, router.asPath, { locale: lng });
};
return (
<div>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('fr')}>Français</button>
</div>
);
};
export default LocaleSwitcher;
Now, you can use the LocaleSwitcher component in your pages. For example, update your pages/index.js file:
// pages/index.js
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useTranslation } from 'react-i18next';
import LocaleSwitcher from '../components/LocaleSwitcher';
export default function Home() {
const { t } = useTranslation('common');
return (
<div>
<h1>{t('welcome')}</h1>
<p>{t('greeting', { name: 'World' })}</p>
<LocaleSwitcher />
</div>
);
}
export async function getStaticProps({ locale }) {
return {
props: {
...(await serverSideTranslations(locale, ['common'])),
},
};
}
Start your Next.js development server:
npm run dev
Navigate to http://localhost:3000 and you should see the application in English. Click on the "Français" button to switch to French, and vice versa.
hreflang tags in your HTML for better SEO when supporting multiple languages.Dynamic locale routing is an essential feature for building multilingual applications with Next.js. By following this tutorial, you should now be able to implement dynamic locale routing in your Next.js project using next-i18next. This setup allows users to switch between languages seamlessly and provides a solid foundation for internationalizing your application.