i18n
No modern app can avoid multi-language support. The framework supports internationalization out of the box.
All internationalization is based on the i18next library.
Detectors
As we are talking about languages, we need some way for the codebase to understand what language the user should use.
This feature is called detectors.
Order of detection:
- X-Lang header
- Query
- User
X-Lang Header Detector
This detector will parse the “X-Lang” header on the request to detect the user's language. The frontend should add the user's language here (“en”, ”fr”, etc.), and if the backend supports it, the app will use the given user language.
“xLang” is the preferred way to work with languages in the framework.
Example for the frontend with Axios:
axios.get("https://example.com/getSomething", {
headers: {
"X-Lang": "en", // Added language
},
});
const api = axios.create({
baseURL: process.env.APP_SERVER_URL,
headers: {
"Content-Type": "application/json",
"X-Lang": "en", // Added language
},
});
// Change it after
api.defaults.headers.common["X-Lang"] = "fr";
Query Detector
The query is a simple detector. Just add the 'lookupQuerystring' parameter to your query string. 'lookupQuerystring' by default is lng, but you can change it as you want inside the config file.
const res = await fetch("https://someUrl.com?lng=en");
User Detector
The user detector tries to find an authorized user (provided by middleware) and grab the ‘locale’ field from this user.
Adding Your Own Detector
At this time, you are not able to add your own detector. Please contact us if you need that option, and we will be happy to help you.
Configuration
Please look at the ‘config/i18n.js’ file for all configuration options. There are a limited number of options available.
Language Files
All files in JSON format are located in ‘src/locales/{localeCode}/translations.json’.
Backends besides files are not supported.
You can find detailed documentation about JSON files in the i18next JSON documentation.
API
The framework provides easy integration for controllers. You can grab the i18n instance with:
req.appInfo.i18n;
req.appInfo.i18n.language; // current language
req.appInfo.i18n.t("some.phrase"); // translate some phrase https://www.i18next.com/overview/api#t
You can pass controller ‘request’ errors as strings for internationalization. They will be processed with i18next.
class SomeController extends AbstractController {
get routes() {
return {
post: {
"/login": {
handler: this.postLogin,
request: yup.object().shape({
email: yup.string().email().required("auth.emailProvided"), // <-- look here i18n
}),
},
},
};
}
}