As an example, this boilerplate has already been translated into 3 different languages - English, French, and German.
Add a new language
To add a new language the following steps are required:
- Add a new locale in the
next-i18next.config.js
file.
module.exports = {
i18n: {
defaultLocale: 'en',
locales: [
'en',
'de',
'fr',
'nl', // <-- add new locale(s) here
],
},
reloadOnPrerender: process.env.NODE_ENV === 'development',
}
-
Create a new directory with the same name as your new locale in the
public/locales
directory. E.g. - if you add a new locale callednl
, create a new directory atpublic/locales/nl
. This directory will contain all the translated strings for your new language. -
Copy all the JSON files in one of the other locale directories to your new locale directory. Translate all the values in the copied files to your new language. To view the translated app, run the app and navigate to
http://localhost:3000/{new-locale}
.
Update translations for existing language
All translation files are located in the public/locales
directory. To modify existing translation strings edit the values in the public/locales/{locale}/{namespace}.json
files.
Basic concepts about internationalization (i18n) explained
To ensure that the correct translation files are loaded for each Next.js page, include the below line in the getStaticProps
or getServerSideProps
function for EVERY page and specify the namespaces of the translation files that are required on the page:
export const getStaticProps: GetStaticProps = async ({ locale }) => {
return {
props: {
... // all other page props
...(await serverSideTranslations(locale, ['common', 'landingPage'])), // <-- add this line to load the common.json and landingPage.json files
},
}
}
To use the correct translation string in a page or component use the useTranslation
hook and specify the namespace(s) that you require on the page.
const Home: React.FC = () => {
const { t } = useTranslation('landingPage') // <-- add this line to use all the strings in the landingPage.json file
return (
<>
<Head>
<title>{t('title')}</title> // <-- add this line to use the "title" value in the landingPage.json file
</Head>
...
</>
)
}
This NPM package was used to implement translations in this boilerplate. Check out the repository for detailed docs and more advanced configuration.