General Translation  
Next.jsConfig

loadTranslation()

API Reference for the loadTranslation() function.

Overview

The loadTranslation() function is the primary way to override the default translation loading behavior. By default, your app will load translations from the GT CDN in production. You can specify a loadTranslation() function to load translations from a different source, such as:

  • From your app's bundle (most common)
  • From a database
  • From an API
  • From a different CDN

We have integrated support for loading translations from local files in your app's bundle. Follow this guide to set up local translations in your Next.js app.

Reference

Parameters

PropTypeDefault
locale
string
-

Description

TypeDescription
localeThe locale for which translations should be loaded.

Returns

A Promise<any> that resolves to either a string or JSX object containing the translations for the given locale.


Setup

Define your loadTranslation() as the default export for a file with the name loadTranslation.js or loadTranslation.ts either in the src/ directory or the root. If you want to use a different name or path, pass the relative path through the loadTranslationPath parameter in withGTConfig().


Examples

Fetching translations from your bundle

When configured to use local translations, the gt-next-cli translate command, translations are saved to the ./public/_gt directory. Just add the --no-publish and --translations-dir ./public/_gt flags to the command.

loadTranslation.js
export default async function loadTranslation(locale) {
  const translations = await import(`../public/_gt/${locale}.json`);
  return translations;
};

Load translations from a CDN

loadTranslation.js
export default async function loadTranslation(locale) {
  try {
    const translations = await fetch(`https://your-cdn.com/translations/${locale}.json`);
    const data = await translations.json();
    return data;
  } catch (e) {
    console.error(e);
    return {};
  }
};

Load translations from your own database

loadTranslation.js
export default async function loadTranslation(locale) {
  try {
    const translations = await prisma.translation.findUnique({
      where: {
        locale: locale,
      },
    });
    return translations;
  } catch (e) {
    console.error(e);
    return {};
  }
};

Notes

  • loadTranslation() gives you the ability to customize how translations are loaded in your app in production.
  • Its most common use case is for adding local translations

Next steps

On this page