Internationalization, often abbreviated as i18n, is the process of designing and developing software that can be adapted to various languages and regions without requiring changes to its source code. This tutorial will guide you through implementing internationalization in your Next.js applications using the built-in next-i18next library.
Next.js provides robust support for internationalization out of the box, making it easier to build globalized web applications. In this section, we'll cover how to set up and use i18n features in a Next.js project.
Before you start, 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 next-i18next library:
npm install next-i18next i18next react-i18next
To enable internationalization in your Next.js project, you need to configure it in the next.config.js file. Create this file if it doesn't already exist:
// next.config.js
const { i18n } = require('./next-i18next.config');
module.exports = {
i18n,
};
Now, create a configuration file for next-i18next named next-i18next.config.js in the root of your project:
// next-i18next.config.js
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
},
};
In this configuration, we've set en as the default locale and added fr (French) as a supported locale.
Next.js uses JSON files to store translations. Create a directory named public/locales in your project root. Inside this directory, create subdirectories for each locale you want to support:
mkdir -p public/locales/en public/locales/fr
Now, add translation files for each locale. For example, create common.json in both directories:
public/locales/en/common.json
{
"welcome": "Welcome to our website",
"hello": "Hello {{name}}!"
}
public/locales/fr/common.json
{
"welcome": "Bienvenue sur notre site web",
"hello": "Bonjour {{name}} !"
}
To use translations in your components, you need to set up the i18next instance and wrap your application with the appWithTranslation higher-order component (HOC). First, initialize i18next:
// pages/_app.js
import { appWithTranslation } from 'next-i18next';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default appWithTranslation(MyApp);
Now, you can use the useTranslation hook in your components to access translations:
// pages/index.js
import { useTranslation } from 'next-i18next';
const Home = () => {
const { t } = useTranslation('common');
return (
<div>
<h1>{t('welcome')}</h1>
<p>{t('hello', { name: 'John' })}</p>
</div>
);
};
export default Home;
In this example, the useTranslation hook is used to access translations from the common namespace. The t function is then used to translate strings.
Next.js supports dynamic routes, and you can use them in conjunction with i18n. For example, let's create a dynamic route for user profiles:
mkdir pages/user/[id]
touch pages/user/[id].js
pages/user/[id].js
import { useRouter } from 'next/router';
import { useTranslation } from 'next-i18next';
const UserProfile = () => {
const router = useRouter();
const { t } = useTranslation('common');
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<div>
<h1>{t('welcome')}</h1>
<p>User ID: {router.query.id}</p>
</div>
);
};
export default UserProfile;
To handle dynamic routes with i18n, you need to configure the getStaticPaths and getStaticProps functions:
// pages/user/[id].js
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
export async function getStaticPaths() {
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } },
],
fallback: true,
};
}
export async function getStaticProps({ locale }) {
return {
props: {
...(await serverSideTranslations(locale, ['common'])),
},
};
}
getStaticProps and getServerSideProps with serverSideTranslations to optimize performance.Internationalization is crucial for building applications that cater to a global audience. Next.js, combined with the next-i18next library, provides a powerful and flexible way to implement i18n features. By following this guide, you should be able to set up internationalization in your Next.js projects and create multilingual web applications efficiently.
Remember to explore the Next.js documentation and the next-i18next GitHub repository for more advanced features and configurations.