I18n vs next-i18next
next-i18next
The next-i18next config file
To configure next-i18next, a config file is required. This tells next-i18next
what your defaultLocale
and other locales are, so that it can preload translations on the server. More information about the config file can be found in the next-i18next docs.
In the project folder, create a new file and name it next-i18next.config.js
.
List the locales in an array, and list the defaultLocale.
module.exports = { i18n: { // all the locales supported in the application locales: ['en-GB', 'en-US'], // the default locale to be used when visiting // a non-localized route (e.g. `/about`) defaultLocale: 'en-GB', }, }
We will then set the fallback language. This is so if we can not provide the preferred language for a user, we can specify another language as fallback. By default, the fallbackLng is set to the defaultLocale. In this case, we do not need to actually set the fallbackLng. Setting the fallbackLng can also increase the page size.
module.exports = { i18n: { // all the locales supported in the application locales: ['en-GB', 'en-US'], // the default locale to be used when visiting // a non-localized route (e.g. `/about`) defaultLocale: 'en-GB', }, fallbackLng: 'en-GB', }
We will then follow the same pattern for the namespaces. Stating the namespaces here allows us to use multiple files within a locale to access translations.
module.exports = { i18n: { // all the locales supported in the application locales: ['en-GB', 'en-US'], // the default locale to be used when visiting // a non-localized route (e.g. `/about`) defaultLocale: 'en-GB', }, fallbackLng: 'en-GB', ns: ['common', 'application', 'validation'], defaultNS: 'application', fallbackNS: 'common',
The localePath
setting configures the path for the localisation files based on the environment. This setting is used to get around issues in deployment with keys rendering instead of translations. More information about this issue can be found in the next-i18next documentation.
module.exports = { i18n: { // all the locales supported in the application locales: ['en-GB', 'en-US'], // the default locale to be used when visiting // a non-localized route (e.g. `/about`) defaultLocale: 'en-GB', }, fallbackLng: 'en-GB', ns: ['common', 'application', 'validation'], defaultNS: 'application', fallbackNS: 'common', // configure the path for localization (i18n) files based on the environment // if the code is running on server side it will use ./public/locales // if the code is running on client side it will use /locales localePath: typeof window === 'undefined' ? require('path').resolve('./public/locales') : '/locales', }