Skip to content

Instantly share code, notes, and snippets.

@aVolpe
Created March 9, 2023 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aVolpe/82a31d2d53b07e3b9680c03b98e6023a to your computer and use it in GitHub Desktop.
Save aVolpe/82a31d2d53b07e3b9680c03b98e6023a to your computer and use it in GitHub Desktop.
i18next react with traduora
export async function setupI18n(config: {
traduora: {
host: string,
projectId: string,
clientId: string,
clientSecret: string
}
}) {
const token = await getTraduoraToken(config.traduora);
return i18n
// load translation using xhr -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
// learn more: https://github.com/i18next/i18next-xhr-backend
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
fallbackLng: 'en',
debug: false,
backend: {
loadPath: `${config.traduora.host}/api/v1/projects/${config.traduora.projectId}/exports?locale={{lng}}&format=jsonflat`,
customHeaders: {
"Accept": "application/octet-stream",
"Authorization": `Bearer ${token}`
}
}
});
}
async function getTraduoraToken(params: { host: string, clientId: string, clientSecret: string }) {
const response = await fetch(`${params.host}/api/v1/auth/token`, {
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
grant_type: 'client_credentials',
client_id: params.clientId,
client_secret: params.clientSecret})
});
if (response.ok) {
const asJson: { access_token: string } = await response.json();
return asJson.access_token;
}
console.warn(response);
throw new Error("Can't get traduora token");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment