Implementing internationalization and localization (i18n) for Next.js Static Site Generation (SSG) pages can be achieved through the following steps:
1. Set up the Next.js Project
First, ensure your Next.js version is 10.0.0 or higher to support built-in i18n routing.
2. Configure next.config.js
In your next.config.js file, enable i18n support and configure language settings and the default locale. For example, if you want to support English and Chinese, configure it as follows:
javascriptmodule.exports = { i18n: { locales: ['en-US', 'zh-CN'], defaultLocale: 'en-US' } }
3. Create Language Resource Files
Create a folder to store resource files for different languages. For example, create a folder for each language under public/locales and add the corresponding translation files:
shellpublic └── locales ├── en-US │ └── common.json └── zh-CN └── common.json
In the common.json file, store the corresponding translation key-value pairs:
json{ "greeting": "Hello" }
4. Use Third-Party Libraries
You can use third-party libraries like next-i18next to simplify and manage language resources. First, install next-i18next:
bashnpm install next-i18next
Then create a next-i18next.config.js configuration file:
javascriptconst { i18n } = require('./next.config'); module.exports = { i18n, localePath: path.resolve('./public/locales') }
5. Implement Language Switching
In your Next.js page, use the useTranslation hook provided by next-i18next to get the translation function and display translated text:
javascriptimport { useTranslation } from 'next-i18next'; export default function HomePage() { const { t } = useTranslation('common'); return <h1>{t('greeting')}</h1>; }
6. Static Site Generation (SSG)
Ensure your page uses getStaticProps to fetch necessary data, including translation files. For example:
javascriptexport const getStaticProps = async ({ locale }) => { return { props: { ...await serverSideTranslations(locale, ['common']) } }; };
This way, Next.js generates static pages for each language during the build process.
7. Deployment and Testing
Deploy your application and verify that pages for each language are correctly generated and accessible.
By following these steps, you can implement multi-language support for Next.js Static Site Generation (SSG) pages.