next-intl - how to connect with Crowdin JS SDK?

336 Views Asked by At

There is a documentation page that recommends Crowdin as localization managment tool. https://next-intl-docs.vercel.app/docs/localization-management

On the page there is an example with integration with github (automate making pull requests but using local files en.json ect).

But We are trying to figure out how to use next-intl with Crowdin JS SDK https://store.crowdin.com/crowdin-api-client-js, so we can download and integrate all translation from Crowdin dashboard and update them live.

Does anyone have an example code how to achieve that with next-intl?

We tried to found an example but did not found it on the documentation website

1

There are 1 best solutions below

5
Andrii Bodnar On

It's not recommended to use the REST API for such cases (due to rate limits and security reasons). Use the Crowdin OTA JS Client instead.

The Crowdin OTA JS Client provides methods to retrieve translation strings from JSON as objects or as plain text for other files. The main advantage here is the AWS CDN (Content Delivery Network) for translations, which provides low latency and high reliability for downloading translations.

For demonstration, I will use the official next-intl example project, and for fetching translations, I will use the getStringsByLocale method.

src/pages/index.tsx:

import otaClient from '@crowdin/ota-client';
import {GetStaticPropsContext} from 'next';
import {useTranslations} from 'next-intl';
import LocaleSwitcher from 'components/LocaleSwitcher';
import PageLayout from 'components/PageLayout';

export default function Index() {
  const t = useTranslations('Index');

  return (
    <PageLayout title={t('title')}>
      <p>{t('description')}</p>
      <LocaleSwitcher />
    </PageLayout>
  );
}

export async function getStaticProps({locale}: GetStaticPropsContext) {
  const client = new otaClient('<distribution-hash>');

  const messages =
    locale === 'en'
      ? (await import(`../../messages/en.json`)).default
      : await client.getStringsByLocale(locale);

  return {
    props: {
      messages
    }
  };
}

Please note that you will need to create a Distribution in your Crowdin project. Distribution is a CDN vault that mirrors the translated content of your project. Then use the distribution hash for the otaClient initialization.

Here are the demos: