# gtx-cli: General Translation CLI tool: Auth URL: https://generaltranslation.com/en/docs/cli/auth.mdx --- title: Auth description: Authenticate your project with General Translation --- ## Usage ```bash npx gtx-cli auth ``` ## Overview Use this CLI command to generate an API key and project ID for your project. This command will: 1. Prompt the user to signin to the General Translation dashboard. 2. Generate an API key and project ID for your project. 3. Create a `.env.local` file in the root of your project and add it to your `.gitignore` file (if it doesn't already exist). 4. Add the API key and project ID to the `.env.local` file. # gtx-cli: General Translation CLI tool: Configure URL: https://generaltranslation.com/en/docs/cli/configure.mdx --- title: Configure description: Configure your project's GT settings --- ## Usage ```bash npx gtx-cli configure ``` ## Overview The `configure` command helps you configure your project's GT settings. It will create a `gt.config.json` file in the root of your project. The file will contain the following settings: - `defaultLocale`: The default locale for your project. - `locales`: An array of [supported locales](/docs/platform/locale-strings#supported-locales) for your project. - `files`: This is an object that contains information about the content you want to translate. For more specific information about the `gt.config.json` file, please see the [config docs](/docs/cli/reference/config). # gtx-cli: General Translation CLI tool: Generate Source Template URL: https://generaltranslation.com/en/docs/cli/generate.mdx --- title: Generate Source Template description: How to generate a source template for your project --- ## Usage ```bash npx gtx-cli generate ``` ## Overview The `gtx-cli generate` command generates a source file for your project for your default locale and supported locales. The generated files are compatible with the `gt-next` and `gt-react` libraries, and are the same format used by the `translate` command. After generating the source files, you can use [local translations](/docs/next/guides/local-tx) to serve the translations to your users. This command is only useful if you are using your own translation service. If you are using the General Translation API, you should use the `translate` command instead. ## Parameters | Parameter | Description | Type | Optional | Default | |-----------------|--------------------------------------------------|---------|----------|-----------------| | `--src ` | Specify the source directory(s) to scan | `[string]` | `true` | `./src && ./app && ./pages && ./components` | | `--dictionary ` | Specify a path to the dictionary file | `string` | `true` | | | `--tsconfig, --jsconfig `| Specify a path to the TS or JS config file | `string` | `true` | | | `--inline` | Include inline `` tags in addition to the dictionary | `boolean` | `true` | `true` | | `--default-locale `| The source locale for the project | `string` | `true` | `en` | | `--ignore-errors` | Ignore errors and force translation for valid content | `flag` | `true` | `false` | ## Setup First, run the `gtx-cli configure` command to configure your project's settings. ```bash npx gtx-cli configure ``` Then, run the `gtx-cli generate` command to generate template files for your project. ```bash npx gtx-cli generate ``` ### Configuration file Read more about the `gt.config.json` file [here](/docs/cli/reference/config). # gtx-cli: General Translation CLI tool: Automatic Translation URL: https://generaltranslation.com/en/docs/cli.mdx --- title: Automatic Translation description: How to automatically translate your project using the General Translation CLI tool --- ```bash npx gtx-cli@latest ``` ## Overview The General Translation CLI tool (`gtx-cli`) allows you to automatically translate your project into any of the [supported languages](/docs/platform/locale-strings#supported-locales). It provides first-class support for [`gt-next`](/docs/react) and [`gt-react`](/docs/react) with your project, allowing you to scan your project for translatable content, translate your project, and generate translation data JSON files. The CLI tool can also be used to generate translations for third-party i18n libraries like [next-intl](https://next-intl.dev/) or [i18next](https://react.i18next.com/). Lastly, the CLI tool can be used to translate JSON, Markdown, MDX, JS, and TS files. A Production API key is required for the `translate` command. Get one for free at [generaltranslation.com](https://generaltranslation.com)! --- Depending on what i18n library your project is using, please follow one of the following tutorials: * [gt-next](/docs/cli/formats/gt) * [gt-react](/docs/cli/formats/gt) * [next-intl](/docs/cli/formats/next-intl-quickstart) * [i18next](/docs/cli/formats/i18next-quickstart) * [JSON](/docs/cli/formats/json) * [Markdown](/docs/cli/formats/mdx) ## Usage | Command | Description | | --- | --- | | [`npx gtx-cli init`](/docs/cli/init) | Run the GT setup wizard. | | [`npx gtx-cli setup`](/docs/cli/setup) | Run the GT React & Next.js setup wizard. | | [`npx gtx-cli configure`](/docs/cli/configure) | Configure your project's GT settings. | | [`npx gtx-cli translate`](/docs/cli/translate) | Translates your project via the GT API. | | [`npx gtx-cli auth`](/docs/cli/auth) | Generate an API key and project ID for your project. | | [`npx gtx-cli scan`](/docs/cli/scan) | Scans your project for translatable content. Can be used repeatedly to update your project. | | [`npx gtx-cli generate`](/docs/cli/generate) | Generates a new translation data JSON file. Should be used when using the library standalone. | # gtx-cli: General Translation CLI tool: Setup Wizard URL: https://generaltranslation.com/en/docs/cli/init.mdx --- title: Setup Wizard description: Run the GT setup wizard --- ## Usage ```bash npx gtx-cli init ``` Use this command to run the GT setup wizard. This command is the same as running `setup`, then running `configure`. The wizard will: 1. Install the necessary dependencies for your project. 2. Help you wrap your JSX content with `` tags (in a React-based project). 3. Create a `gt.config.json` file in the root of your project. 4. Generate an API key and project ID for your project. ## Dependencies The `init` command will install the following dependencies for your project: - `gt-react` or `gt-next` (if your project is React-based) - `gtx-cli` as a dev dependency (if not already installed) ## React-based projects If your project is React-based, the wizard will help setup your project to use `gt-react` or `gt-next`. If you are already using a different i18n library, you may need to manually setup your project. See the [React docs](/docs/react/tutorials/quickstart) or the [Next.js docs](/docs/next/tutorials/quickstart) for more information. Since the wizard is currently experimental, it is possible that it may not work for all React-based projects. In these cases, you may need to manually setup your project. If you encounter any issues, please let us know on [GitHub](https://github.com/generaltranslation/gt/issues). This part of the wizard can also be ran independently via `npx gtx-cli setup`. ## `gt.config.json` The `init` command helps you configure your project's GT settings. It will create a `gt.config.json` file in the root of your project. The file will contain the following settings: - `defaultLocale`: The default locale for your project. - `locales`: An array of [supported locales](/docs/platform/locale-strings#supported-locales) for your project. - `files`: This is an object that contains information about the content you want to translate. For more specific information about the `gt.config.json` file, please see the [config docs](/docs/cli/reference/config). This part of the wizard can also be ran independently via `npx gtx-cli configure`. ## Credentials The wizard will help you generate an API key and project ID for your project (if they are not already set up). Please note that the API key and project ID are not required to use `gt-react` or `gt-next`. The wizard will add the API key and project ID to your `.env.local` file. If this file does not exist, the wizard will create it and add it to your `.gitignore` file. This part of the wizard can also be ran independently via `npx gtx-cli auth`. # gtx-cli: General Translation CLI tool: Scan URL: https://generaltranslation.com/en/docs/cli/scan.mdx --- title: Scan description: Scans your project for translatable content --- ## Usage ```bash npx gtx-cli scan ``` ## Overview The `gtx-cli scan` command scans your project for translatable content. It does this by parsing your project's file tree and using babel to wrap the `` component around static content. Any dynamic content will be automatically wrapped with `` components. This command is similar to the `setup` command, but it is more straightforward and only wraps the `` component around content. It does not add other components like ``. Thus, we recommend running this command occasionally to ensure all the content in your project is translatable. **You should run `setup` the first time you are integrating General Translation into your project.** ```jsx title="src/app/Home.js" import { T, Var } from 'gt-next'; // [!code highlight] export default function Home({ user }) { return (
{/* [!code highlight] */} Hello, World! My name is { user.name }
); } ``` --- ## Parameters | Parameter | Description | Type | Optional | Default | |-----------------|--------------------------------------------------|---------|----------|-----------------| | `--src ` | The source directory to scan | `string` | `true` | `./src && ./app && ./pages && ./components` | | `--config ` | The path to the GT config file | `string` | `true` | `"gt.config.json"` | | `--disable-ids` | Disable the automatic generation of IDs for `` components | `flag` | `true` | `false` | | `--disable-formatting` | Disable auto-formatting | `flag` | `true` | `false` | --- ## Behavior ### The `id` prop The scan command will automatically generate unique IDs for your `` components. This is useful for projects that use a lot of `` components and want to avoid manually having to assign each one a unique ID. This `id` is useful for referencing specific translations in the translation editor and in the console. To disable this behavior, you can use the `--disable-ids` flag. ### `` injection behavior #### Basic case The CLI will wrap JSX elements at the highest possible level. This means that it will wrap the entire component in a `` component if it is not already wrapped. ```jsx
Hello, World!
->
Hello, World!
``` See the [reference](/docs/cli/reference/wrapping) for more details on how the `` component is wrapped. ### Auto-formatting The scan command will automatically format the changes it makes to your codebase with Prettier, Biome, or ESLint depending on your project's configuration. To disable this behavior, you can use the `--disable-formatting` flag. # gtx-cli: General Translation CLI tool: React Setup URL: https://generaltranslation.com/en/docs/cli/setup.mdx --- title: React Setup description: Integrates gt-next or gt-react with your project. --- ## Usage ```bash npx gtx-cli setup ``` ## Overview The `gtx-cli setup` command automatically sets up your project for translation with `gt-next` or `gt-react`. It does this by parsing your project's file tree and using babel to wrap the `` component around static content. Any dynamic content will be automatically wrapped with `` components. This command is run as part of the `init` setup wizard. Additionally, this command can be ran independently via `npx gtx-cli setup`. This command should be ran **once**, when you are first internationalizing your project. On subsequent changes, you should use the `scan` command to update your project. See the [scan](/docs/cli/scan) command for more details. ```jsx title="src/app/Home.js" import { T, Var } from 'gt-next'; // [!code highlight] export default function Home({ user }) { return (
{/* [!code highlight] */} Hello, World! My name is { user.name }
); } ``` If your project is using the Next.js App Router, the setup command will add a `` component within the appropriate `layout.jsx` file. --- ## Parameters | Parameter | Description | Type | Optional | Default | |-----------------|--------------------------------------------------|---------|----------|-----------------| | `--src ` | The source directory to scan | `string` | `true` | `./src && ./app && ./pages && ./components` | | `--config ` | The path to the GT config file | `string` | `true` | `"gt.config.json"` | --- ## Behavior ### Configuration file When running the CLI tool for the first time, it will attempt to create a `gt.config.json` file in the root of your project. This file contains metadata about your project that is used to translate your content. Read more about the `gt.config.json` file [here](/docs/cli/reference/config). ### The `id` prop The setup command gives the option of automatically generating unique IDs for your `` components. This is useful for projects that use a lot of `` components and want to avoid manually having to assign each one a unique ID. This `id` is useful for referencing specific translations in the translation editor and in the console. ### `` injection behavior #### Basic case The CLI will wrap JSX elements at the highest possible level. This means that it will wrap the entire component in a `` component if it is not already wrapped. ```jsx
Hello, World!
->
Hello, World!
``` See the [reference](/docs/cli/reference/wrapping) for more details on how the `` component is wrapped. ### `` behavior For the Next.js App Router, the setup command will automatically wrap the `` component in a `` component within the appropriate `layout.jsx` file. Additionally, it will setup the `withGTConfig` Next.js plugin in the `next.config.js` file for you. ### Auto-formatting The setup command will automatically format the changes it makes to your codebase with Prettier, Biome, or ESLint depending on your project's configuration. # gtx-cli: General Translation CLI tool: Stage URL: https://generaltranslation.com/en/docs/cli/stage.mdx --- title: Stage description: How to stage your translations for review --- ## Overview `gtx-cli stage` is a command that generates translations for your project and stages them for review. This command is only useful if you've enabled human review on your project. Currently, this command is only supported for apps using `gt-next` or `gt-react`. ## Usage Run this in your CI pipeline **before** you build your app for production. ```bash npx gtx-cli stage ``` **Note:** This command requires a production API key! Get one on the [platform](https://generaltranslation.com/dashboard). The `gtx-cli stage` command works in the same way as the `translate` command, but instead of downloading the completed translations or publishing them to the CDN, it simply stages them for review. After running `gtx-cli stage`, you should run `gtx-cli translate` to complete the process and download the translations (if configured to do so). **For Production Use Only!** This command is meant for production builds and **should not be used in development**. Before running this command, please make sure you are on the branch that will be used for production. Remember to also specify your production API key (`GT_API_KEY`) and Project ID (`GT_PROJECT_ID`) in your environment variables. --- ## Flags | Parameter | Description | Type | Optional | Default | |-----------------|--------------------------------------------------|---------|----------|-----------------| | `--api-key` | Specify a production API key | `string` | `true` | | | `--project-id` | Specify the project ID | `string` | `true` | | | `--version-id` | Specify a version ID (by default, a hash of the content) | `string` | `true` | | | `--config `| Specify a path to the GT config file | `string` | `true` | `"gt.config.json"` | | `--tsconfig, --jsconfig `| Specify a path to the TS or JS config file | `string` | `true` | | | `--src ` | Specify the source directory(s) to scan | `[string]` | `true` | `./src && ./app && ./pages && ./components` | | `--dictionary ` | Specify a path to the dictionary file | `string` | `true` | | | `--inline` | Include inline `` tags in addition to the dictionary | `boolean` | `true` | `true` | | `--timeout` | The timeout for the translation request in seconds | `number` | `true` | `600` | | `--new, --locales `| Locales to translate your project into | `[string]` | `true` | | | `--default-locale `| The source locale for the project | `string` | `true` | `en` | | `--ignore-errors` | Ignore errors and force translation for valid content | `flag` | `true` | `false` | | `--dry-run` | Dry run the command | `flag` | `true` | `false` | All of these parameters are optional. Do not add your API key to the `gt.config.json` file! You should set it as an environment variable instead. The CLI will automatically read `GT_API_KEY` if it is set. There are a few key parameters: | Parameter | Description | |-----------------|--------------------------------------------------| | `--dry-run` | This flag will cause the CLI to parse and validate your project, but will not communicate with the GT API. This is useful for validating your codebase. | `--api-key` | Unless you are using `--dry-run`, you must provide a production API key. | `--project-id` | Similarly, unless you are using `--dry-run`, you must provide a project ID. | `--new, --locales ` | Locales to translate your project into. These will be appended to the locales specified in your `gt.config.json` file. ### Configuration file When running `gtx-cli stage`, the CLI will automatically add the `stageTranslations : true` property to your `gt.config.json` file. This property ensures that if `translate` is ran without first running`stage` for a specific deployment version, the CLI tool will error and exit. Additionally, this property ensures that the `translate` command will not duplicate the translations done by the `stage` command. # gtx-cli: General Translation CLI tool: Translate URL: https://generaltranslation.com/en/docs/cli/translate.mdx --- title: Translate description: How to translate your project --- ## Usage Run this in your CI pipeline **before** you build your app for production. ```bash npx gtx-cli translate ``` **Note:** This command requires a production API key! Get one on the [platform](https://generaltranslation.com/dashboard). ## Overview The `gtx-cli translate` command translates your project. It traverses your project's file tree and translates any content wrapped in a `` component or using the `useGT()` functions. Additionally, it includes content from the dictionary file (if one is provided). This command is the primary way of using the General Translation API and related services. **For Production Use Only!** This command is meant for production builds and **should not be used in development**. Before running this command, please make sure you are on the branch that will be used for production. Remember to also specify your production API key (`GT_API_KEY`) and Project ID (`GT_PROJECT_ID`) in your environment variables. ## Usage There are 3 ways to use the `translate` command. Methods 1 and 2 require a production API key: We recommend running the setup wizard: [`npx gtx-cli configure`](/docs/cli/configure) to help configure your project before running the `translate` command. Depending on how your project is configured, the behavior of the translate command may change. ### Method 1: Translate your project's JSON files. [#translate-json] If you are using other i18n libraries such as `next-intl`, `react-i18next`, or `next-i18next`, you can use this method to translate your project's JSON files. Translations will be automatically saved to your codebase. To use the CLI tool to translate your project's JSON files, modify your `gt.config.json` file to include `json` in the `files` property. See the [CLI config docs](/docs/cli/reference/config#json) for more details. ```bash npx gtx-cli translate ``` The CLI tool will automatically detect your i18n library by reading your `package.json` file, and will translate your JSONs while respecting your i18n library's syntax. ### Method 2: Translate your GT project. If your project is using `gt-next` or `gt-react`, you can use this method to generate translations for your project. ```bash npx gtx-cli translate ``` By default, translations are saved to the GT CDN. However, if you would like to save the translations to your codebase, add the `gt` property to the `files` object in the `gt.config.json` file. `gt-next` and `gt-react` support serving translations locally, as well as using General Translation's public CDN. We recommend using the CDN for reduced latency, better performance, and smaller bundle sizes. See the [CLI config docs](/docs/cli/reference/config#gt) for more details. ### Method 3: Validate your project's `` components and dictionary file. [#validate] This method is useful for validating your project's `` components and dictionary file. This ensures that your project is correctly configured and that the translations will be valid and accurate. No translations will be generated if the `--dry-run` flag is provided. ```bash npx gtx-cli translate --dry-run ``` --- ## Flags | Parameter | Description | Type | Optional | Default | |-----------------|--------------------------------------------------|---------|----------|-----------------| | `--api-key` | Specify a production API key | `string` | `true` | | | `--project-id` | Specify the project ID | `string` | `true` | | | `--version-id` | Specify a version ID (by default, a hash of the content) | `string` | `true` | | | `--config `| Specify a path to the GT config file | `string` | `true` | `"gt.config.json"` | | `--tsconfig, --jsconfig `| Specify a path to the TS or JS config file | `string` | `true` | | | `--src ` | Specify the source directory(s) to scan | `[string]` | `true` | `./src && ./app && ./pages && ./components` | | `--dictionary ` | Specify a path to the dictionary file | `string` | `true` | | | `--inline` | Include inline `` tags in addition to the dictionary | `boolean` | `true` | `true` | | `--timeout` | The timeout for the translation request in seconds | `number` | `true` | `600` | | `--new, --locales `| Locales to translate your project into | `[string]` | `true` | | | `--default-locale `| The source locale for the project | `string` | `true` | `en` | | `--ignore-errors` | Ignore errors and force translation for valid content | `flag` | `true` | `false` | | `--dry-run` | Dry run the command | `flag` | `true` | `false` | All of these parameters are optional. Do not add your API key to the `gt.config.json` file! You should set it as an environment variable instead. The CLI will automatically read `GT_API_KEY` if it is set. There are a few key parameters: | Parameter | Description | |-----------------|--------------------------------------------------| | `--dry-run` | This flag will cause the CLI to parse and validate your project, but will not communicate with the GT API. This is useful for validating your codebase. | `--api-key` | Unless you are using `--dry-run`, you must provide a production API key. | `--project-id` | Similarly, unless you are using `--dry-run`, you must provide a project ID. | `--new, --locales ` | Locales to translate your project into. These will be appended to the locales specified in your `gt.config.json` file. ### Configuration file When running the CLI tool for the first time, it will attempt to create a `gt.config.json` file in the root of your project. This file contains metadata about your project that is used to translate your content. Read more about the `gt.config.json` file [here](/docs/cli/reference/config). ## Important Tips ### Content Sources The `translate` command will recursively search for translatable content in your project. By default, it searches in the following directories: - `./src` - `./app` - `./pages` - `./components` You can specify alternate directories to search by using the `--src` flag, or by modifying the `src` property in your [`gt.config.json`](/docs/cli/reference/config) file. ### Dictionary File The `translate` command will automatically detect the dictionary file in your project. By default, it looks for a file named `dictionary.[json|ts|js]` in the following directories: - `./src` - `./` You can specify an alternate dictionary file by using the `--dictionary` flag, or by modifying the `dictionary` property in your [`gt.config.json`](/docs/cli/reference/config) file. # generaltranslation: General Translation Core SDK: Core URL: https://generaltranslation.com/en/docs/core.mdx --- title: Core description: Docs for General Translation's core libraries --- ## Installation `gt-next`, `gt-react`, and `gtx-cli` all depend on the `generaltranslation` package. You can also install `generaltranslation` separately. ```bash npm i generaltranslation ``` ```bash yarn generaltranslation ``` ```bash bun generaltranslation ``` ```bash pnpm generaltranslation ``` ## Usage import Construction from "@/components/mdx/construction"; # key-concepts: Dynamic Content URL: https://generaltranslation.com/en/docs/key-concepts/dynamic-content.mdx --- title: Dynamic Content description: A brief overview of working with Dynamic Content in GT. --- ## Overview **Dynamic Content** is generally any content that can change based on the user, context, environment, etc. This exists in contrast to **Static Content**, which remains the same regardless of the user, context, environment, etc. TL;DR * Static Content never changes (raw strings, text, etc.). * Dynamic Content can change (names, emails, time, language, etc.). **What is Static Content?** Static Content generally refers to any raw text that exists in the bundle that is served to your users. A good rule of thumb is any text or strings that a developer can read in the source code is static text. For example, consider this file: ```jsx title="Landing.jsx" copy export default function Landing() { return ( <> Welcome to my app! ); } ``` The text, "Welcome to my app!", is Static Content because it never changes. But, what if we wanted to change the page such that it would respond if the user was logged in: ```jsx title="Landing.jsx" copy export default function Landing(user) { if (user) { return (

Welcome to my app, {user.name}!

); } return (

Welcome to my app!

); } ``` Even though these two phrases are being conditionally rendered, these two phrases are both considered static text. Remember our rule of thumb: we can see this content by reading the source code in `landing.jsx`. However, `{user.name}` is considered dynamic content, because it can change. We cannot know what will get rendered on the user's screen by just reading the `landing.jsx` file.
## "To Tx or not to Tx" Sometimes, we want to translate dynamic content, but other times we want it to remain the same. A good example would be a user's email address or name. Another example might be a bank account balance or a user's SSN. Such items are (1) not likely to need translation when your app is being rendered in a different language and (2) can vary (in this case between each user). ### Example ```jsx title="Greeting.jsx" copy import { T, Var } from 'gt-next' export default function Greeting(name) { return ( Hello, {name}! ); } ``` As far as translation goes this has two benefits: 1. You do not have to create a translation for every possible name. * Using ``, we only generate one translation that essentially would look like this: * \`¡Hola, $\{name\}!\` * If we do not use ``, we would have to perform an on-demand translation for every unique name: * "¡Hola, Alice!", "¡Hola, Bob!", "¡Hola, Charlie!", "¡Hola, David!", ... 2. You also don't have to worry about the names themselves changing into a translated form of their name: (i.e. "¡Hola, Alicia!", "¡Hola, Roberto!", ...). As you can see, the `` component should be used to wrap any contents that should remain the same regardless of locale. This way, we avoid the need to create translations for every possible value of the dynamic content. By wrapping private information in a `` component, you can ensure that the information is not sent to the General Translations API. **Exceptions** The exceptions to the statement above is (1) in the case of a nested `` component used inside of a `` component (ie, the children of the nested `` component will be translated) or (2) when data is passed intentionally to our API via some other means within a child of the `` component (i.e., a fetch call). However, this is not the intended use of the `` component nor the General Translations API and doing so can harm load times and performance. # key-concepts: Private Information URL: https://generaltranslation.com/en/docs/key-concepts/private-information.mdx --- title: Private Information description: A brief overview of working with Private Information in GT. --- ## Overview Private information is generally any information that should remain private. For example, a user's Social Security Number (SSN), Tax Identification Number (TIN), or email address. In order to keep this information private while translating, we use the `` component. The `` component is used to wrap any content that should not be shared, and the content inside the `` component will always remain the same. This is great for names, emails, addresses, etc. Sometimes, we do want to display private information, but we still need to reformat it based on the user's preferred languages, regional regulations, etc. For example, we might want to display a user's bank account balance in their local currency. In these cases, we instead use either ``, ``, or `` components. ### Example The `` component is also useful for displaying private information. ```jsx title="PrivateInfo.jsx" copy import { T, Var } from 'gt-next' export default function PrivateInfo(email) { return ( Your email address is {email}. ); } ``` The children of the `` component will not be translated. Its contents will never be passed to the General Tranlsation API. Its contents will not be distrubuted to the CDN. # key-concepts: On-Demand vs Proactive Translation URL: https://generaltranslation.com/en/docs/key-concepts/tx-loading.mdx --- title: On-Demand vs Proactive Translation description: What is the difference between performing translation on-demand and translating ahead of time? --- # gt-next: General Translation Next.js SDK: Next.js Quickstart URL: https://generaltranslation.com/en/docs/next.mdx --- title: Next.js Quickstart description: Easily internationalize your Next.js App with gt-next --- ## Overview This quickstart guide will walk you through how to setup your Next.js application with `gt-next`. By the end of this guide, you will have a Next.js app that is ready to start translating content. In this guide, we will cover the following: Installation Configuration Usage Testing Your App Deployment ### Prerequisites - A Next.js application using the App Router - Basic knowledge of Next.js and JavaScript ## Installation Install the `gt-next` and `gtx-cli` packages: ```bash npm i gt-next npm i --save-dev gtx-cli ``` ```bash yarn add gt-next yarn add --dev gtx-cli ``` ```bash bun add gt-next bun add --dev gtx-cli ``` ```bash pnpm add gt-next pnpm add --save-dev gtx-cli ``` --- **Automatic Setup:** We have an experimental Setup Wizard that can help you setup your project with `gt-next`. Try it out by running `npx gtx-cli@latest`. You'll still need to manually internationalize strings, but it will help you get started. See the [Setup Wizard](/docs/cli/init) reference guide for more information. Alternatively, if you would like your AI tool like Claude Code, Cursor, or Windsurf to automatically setup your project, you can use our [mcp server](/docs/platform/ai-tools). ## Configuration ### `withGTConfig` The `withGTConfig` function is a function that is used to initialize the SDK in a Next.js application. Place this in your `next.config.[js|ts]` file. ```tsx title="next.config.ts" import { withGTConfig } from 'gt-next/config'; const nextConfig = { // Your next.config.ts options }; export default withGTConfig(nextConfig, { // Additional GT configuration options }); ``` See the [withGTConfig API Reference](/docs/next/api/config/withGTConfig) for more information. ### `GTProvider` `gt-next` also exports a `GTProvider` component. This component is used to provide context to client-side components in your Next.js application. The `GTProvider` and `withGTConfig` work together to provide context to your application. This context includes: - Managing the user's current locale - The relevant translations for that locale - Context for the `useGT` hook - Context for the `useDict` hook First, add the `GTProvider` component to the root layout of your application. It should be placed as high up in your component tree as possible. ```tsx copy title="src/layout.tsx" import { GTProvider } from 'gt-next'; export default function RootLayout({ children }) { return ( {children} ); } ``` If you have multiple root layouts, place the `GTProvider` in each one. Next, create a [`gt.config.json`](/docs/cli/reference/config) file in the root of your project. This file is used to configure both the `gtx-cli` tool and the `gt-next` library. ```json title="gt.config.json" copy { "defaultLocale": "en", "locales": ["fr", "es"] } ``` You should customize the `defaultLocale` and `locales` to match your project. See the list of [supported locales](/docs/platform/locale-strings) for more information. `withGTConfig` will automatically detect the `gt.config.json` file in your project, and use it to configure the SDK. ### Environment Variables Set the following environment variables: ```bash copy GT_API_KEY="" # Your General Translation Developer API key GT_PROJECT_ID="" # Your General Translation project ID ``` **Make sure your API key variable is only set in your development environment! It should not be set in production.** You can get a free API key and project ID by creating a [General Translation account](https://dash.generaltranslation.com/signup). After creating an account, navigate to the [Development API Keys](https://dash.generaltranslation.com/settings/dev-api-keys) page to get your Dev API key and project ID. Alternatively, you can also use the CLI tool command [`npx gtx-cli auth`](/docs/cli/auth) to generate an API key and project ID for your project, saved to your `.env.local` file. `gt-next` is an i18n library that can work standalone without any environment variables. Without them, the library will act very similarly to other i18n libraries, and will still have core internationalization functionality. However, `gt-next` also offers a native integration with the General Translation platform. This integration unlocks additional functionality in the library, such as: - Translation Hot Reloading in Development - Automatic AI translations - Syncing translations with the General Translation platform - Native integration with our translation CDN - On-demand translation of React components in production (on the server side) To avoid using the General Translation platform, just don't set any environment variables. --- ## Usage Great! If you've followed the steps above, your Next.js app is now setup to use `gt-next`. The next step is to internationalize your content. Here, we'll give a brief overview of the different ways to translate content in your application. ### `` Component The `` component is the main component for translating JSX content in your application. To use it, simply wrap the JSX you want to translate in the `` component. ```tsx import { T } from 'gt-next';
Your content
``` If you have dynamic content, you'll need to use [variable components](/docs/next/guides/variables) to pass in the dynamic values. ```tsx import { T, Var } from 'gt-next';
Hello, {name}!
``` See the [Translating JSX](/docs/next/guides/jsx) guide for more information. ### `useGT` Hook The `useGT` hook is a React hook that returns a function that can be used to translate strings. ```tsx import { useGT } from 'gt-next/client'; const translate = useGT(); translate('Hello, world!'); ``` The `useGT` hook is a client-side hook, and should only be used in client-side components. For server-side components, use the async `getGT()` function instead. See the [Translating Strings](/docs/next/guides/strings) guide for more information. Utilizing the hot-reload translation functionality will be helpful for internationalizing your application. To enable this, make sure you have the `GT_API_KEY` and `GT_PROJECT_ID` environment variables set in your development environment. --- ## Testing Your App Congratulations! 🥳 If you've followed the steps above, your app is now multilingual! Let's see it in action. ### See Your App in a Different Language Add the [``](/docs/next/api/components/localeSelector) component to your app. This will allow you to select a different language for your app. **Tip:** You can also skip this step and just change your language in your browser settings. Start your Next.js app in development mode. ```bash npm run dev ``` ```bash yarn run dev ``` ```bash bun run dev ``` ```bash pnpm run dev ``` Open up your app in your preferred browser (usually at [http://localhost:3000](http://localhost:3000)). ### Troubleshooting **Browser Cookies** If you are deciding to test different languages by changing your browser's language, this issue may occur. Check your browser's cookies for your app. General translation uses cookies to store the user's language preference. The cookie is called `generaltranslation.locale`, and all you need to do is delete it. Then, just double check you are using the desired perferred language and then refresh the page. How to check cookies: * [Chrome](https://support.google.com/chrome/answer/95647) * [Firefox](https://support.mozilla.org/en-US/kb/delete-cookies-remove-info-websites-stored) * [Safari](https://support.apple.com/en-mn/guide/safari/sfri11471/16.0/mac/11.0) * [Edge](https://support.microsoft.com/en-us/microsoft-edge/delete-cookies-in-microsoft-edge-63947406-40ac-c3b8-57b9-2a946a29ae09) **On-Demand Translation** You may notice when loading languages in development, translations will take a few seconds to be displayed. This happens because your app is being translated in real time. We refer to this process as an "on-demand translation". This **only happens in dev** so you can easily prototype your website in different languages. All translations are preloaded in production, so there will be no delay. Follow our guide on [shipping to production](/docs/next/tutorials/quickdeploy). **JSX Translation** Right now, the wizard automatically adds `` components around text content. We are currently working on a solution that automatically setup string translations. Until then, if you are rendering a string, please follow [this guide](/docs/next/guides/strings) for translating strings. The most likely cause of an inaccurate translation is ambiguous wording. For example, "apple" can be a fruit or a technology company. To fix this, you can provide more context to the translation with the `context` prop. The [``](/docs/next/api/components/t), [`useGT()`](/docs/next/api/strings/useGT), and [`getGT()`](/docs/next/api/strings/getGT) functions all support a `context` prop. For example: ```jsx Apple ``` --- ## Deployment Great! If you're satisfied with your translations and the functionality of your app, you can now deploy your application. The behavior of `gt-next` in production is slightly different from development. Specifically, no translations will be performed at runtime (with the exception of the `` component & `tx` function). This means that you'll need to translate your content before deploying your application, in the build process. Luckily, the `gtx-cli` tool has a `translate` command that can be used to automatically translate your content. First, you'll need to get a Production API key from the [General Translation platform](https://dash.generaltranslation.com). Please note that this key is different from your Development API key, and begins with `gtx-api-`, instead of `gtx-dev-`. Read about the difference between Development and Production keys [here](/docs/next/concepts/environments). Add this environment variable to your CI/CD pipeline. ```bash GT_PROJECT_ID= GT_API_KEY= ``` Make sure that `GT_API_KEY` is **NOT** prefixed with `NEXT_PUBLIC_`! If it is, you'll risk exposing your API key to the public. Run the `translate` command to translate your content. ```bash npx gtx-cli translate ``` You can configure the behavior of the `translate` command with the [`gt.config.json`](/docs/cli/reference/config) file. See the [CLI Tool](/docs/cli/translate) reference guide for more information. Add the `translate` command to your build process. ```json title="package.json" copy { "scripts": { "build": "npx gtx-cli translate && <...YOUR_BUILD_COMMAND...>" } } ``` If you're not using the General Translation platform, you can still use `gt-next` in production. However, you'll need to manually translate your content before deploying your application. Instead of running `translate`, run the `generate` command to generate JSON files containing all of your translation data (in your source language). ```bash npx gtx-cli generate ``` Then, you'll need to manually edit / translate these files, and load them into your application with [`loadTranslations`](/docs/next/guides/local-tx). --- ## Summary * In this guide, we covered how to setup your Next.js app with `gt-next` * We briefly covered the different ways to translate content in your application. * We also covered how to deploy your application after you've internationalized your content. ## Next Steps - Learn about how to translate JSX content with the `` component: [Translating JSX](/docs/next/guides/jsx) - Learn about how to translate strings with the `useGT` hook: [Translating Strings](/docs/next/guides/strings) - Learn how to use local translations: [Local Translations](/docs/next/guides/local-tx) # gt-next: General Translation Next.js SDK: Overview URL: https://generaltranslation.com/en/docs/next/introduction.mdx --- title: Overview description: Overview of General Translation's Next.js SDK --- ## Introduction The General Translation Next.js SDK is an open-source internationalization (i18n) library for Next.js. It offers a set of tools to help you internationalize your Next.js application in a easy and maintainable way, with feature parity to other popular i18n libraries. It is built on top of the [React SDK](/docs/react), and offers additional features specific to Next.js. The Next.js SDK can be used without the General Translation platform, and will act very similarly to other i18n libraries. However, it also integrates with our platform, offering additional features such as: - Translation Hot Reloading in Development - Automatic AI translations - Syncing translations with the General Translation platform - Native integration with our translation CDN - On-demand translation of React components in production (on the server side) ## Concepts There are 5 main concepts to understand about the SDK. Initialization with `withGTConfig` The `` component The `` component The `useGT` hook (Optional) The `useDict` hook ## Initialization with `withGTConfig` The `withGTConfig` function is a function that is used to initialize the SDK in a Next.js application. It should be placed in your `next.config.[js|ts]` file, and is used to configure the SDK. ```tsx title="next.config.ts" import { withGTConfig } from 'gt-next/config'; const nextConfig = { // Your next.config.ts options }; export default withGTConfig(nextConfig, { // Your GT configuration }); ``` See the [withGTConfig API Reference](/docs/next/api/config/withGTConfig) for more information. ## The `` component ```tsx import { GTProvider } from 'gt-next'; ``` The `` component is the main component that you need to add to your application. It is used to provide the rest of your application with context. This context includes the current language and the relevant translations for that language. The provider is only required if you are using any client-side features. If you are only using server-side features, the provider is not required, but can still be included. ### Important Considerations - The provider should wrap your entire application. - Ideally, it should be placed as high in the tree as possible, such as in your root layout. See the [GTProvider](/docs/next/api/components/gtprovider) page for more information. ## The `` component The `` component is the recommended way to translate content in your application. It is a React component that can be used to wrap any JSX element, and will automatically render the content of the element into a supported language. We recommend using the `` component wherever possible, since it allows for the most flexibility in translations. Unlike strings, the `` component can be used to translate HTML content, making it much more powerful than string translations. ### Examples ```tsx
Hello, world!
``` ```tsx

Here is an image

Example
``` ```tsx Formatting can be done easily with the `` component. {1000} {new Date()} {1000} ``` See the [components](/docs/next/guides/jsx) guide to learn about the different ways to use the `` component. See the [T API Reference](/docs/next/api/components/t) for the API of the `` component. ## The `useGT` hook The `useGT` hook is a React hook that can be used similarly to the `` component, with some trade-offs. The hook returns a function that can be used to translate strings. ```tsx const translate = useGT(); translate('Hello, world!'); ``` Compared to the `` component, the `useGT` hook allows for more flexibility in your codebase. For example, if you have a complex data structure with nested strings, a `` component would be more difficult to use. ```tsx const t = useGT(); const data = { title: t('Hello, world!'), description: t('This is a description'), }; ``` See the [strings](/docs/next/guides/strings) guide to learn more about the `useGT` hook. See the [useGT API Reference](/docs/next/api/strings/useGT) for more information. ## The `useDict` hook The `useDict` hook is a React hook that returns a function that can be used to retrieve translations for a given key. ```tsx title="dictionary.ts" const dictionary = { hello: { world: 'Hello, world!', }, }; ``` ```tsx title="App.tsx" const translate = useDict(); translate('hello.world'); ``` This behavior is similar to other translation libraries, such as `react-i18next` and `next-intl`. We do not recommend using the `useDict` hook in your application. Frequent use of the `useDict` hook will make your codebase more difficult to maintain, and will lead to large tech debt. Instead, we recommend using the `` component or the `useGT` hook. If you are migrating from another i18n library, the `useDict` hook is a drop-in replacement and can useful for incrementally migrating your codebase. See the [dictionaries](/docs/next/guides/dictionaries) guide to learn more about the `useDict` hook. See the [useDict API Reference](/docs/next/api/dictionary/useDict) for more information. --- ## Next Steps - Learn about how to setup your Next.js project with the SDK: [Quickstart](/docs/next) - Learn about how to translate strings with the `useGT` hook: [Translating Strings](/docs/next/guides/hooks) - Learn about how to translate JSX content with the `` component: [Translating JSX](/docs/next/guides/jsx) # General Translation Platform: AI Tools URL: https://generaltranslation.com/en/docs/platform/ai-tools.mdx --- title: AI Tools description: General Translation support for AI Tools including llms.txt and MCP server --- ## Overview We provide several tools to help your AI tools work with General Translation. ## llms.txt Provide your AI tools with our [llms.txt](/llms.txt) file for a brief summary of our docs in a LLM-friendly format. ## llms-full.txt Provide your AI tools with our [llms-full.txt](/llms-full.txt) file for the full content of our docs in a LLM-friendly format. ## MCP Server We offer a simple MCP server that AI tools like Cursor, Windsurf, and Claude Code can use to access our docs. Add the following to your mcp config file to use our MCP server. ### Local MCP Server For AI tools which maintain a persistent connection such as **Windsurf**, **Cursor**, and **Claude Code**, you can run our MCP docs server locally. ```json title="mcp.json" copy { "mcpServers": { "generaltranslation": { "command": "npx", "args": ["-y", "@generaltranslation/mcp@latest"] } } } ``` ### Streamable-HTTP Otherwise, you can use our MCP server hosted at `https://mcp.gtx.dev`. ```json title=".mcp.json" { "mcpServers": { "generaltranslation": { "type": "streamable-http", "url": "https://mcp.gtx.dev" } } } ``` ### SSE For tools that don't support streamable-http, you can use the SSE endpoint instead. ```json title=".mcp.json" { "mcpServers": { "generaltranslation": { "type": "sse", "url": "https://mcp.gtx.dev/sse" } } } ``` ## Using the MCP Server Make sure you've added the MCP server to your mcp config file. ### Cursor To use the MCP server in Cursor, simply ask the AI to use the `generaltranslation` tool. For example, you can ask the AI: "Use the generaltranslation tool to explain how to use a `` component." ### Windsurf To use the MCP server in Windsurf, ask the AI to use the `generaltranslation` mcp server. For example, you can ask the AI: "Use the generaltranslation mcp server to explain how to use a `` component." ### Claude Code To use the MCP server in Claude Code, ask the AI to use the `generaltranslation` mcp server. # General Translation Platform: API Keys URL: https://generaltranslation.com/en/docs/platform/apikeys.mdx --- title: API Keys description: How to use API keys with General Translation --- ## Overview There are two types of API keys used with General Translation: - **Production API Key**: This is used to translate your content in production. - **Development API Key**: This is used to translate your content in development. The behavior between the two types of keys are different, so you should be careful to use the correct key for the environment you are in. ```bash GT_PROJECT_ID=your-project-id GT_API_KEY=your-api-key ``` If you are using `gt-next` or `gt-react` as a standalone i18n library, you do not need to use API keys. --- ## How to obtain Navigate to your project dashboard on the [General Translation website](https://generaltranslation.com). Click on the "API Keys" or "Developer Keys" tab. Click on the "Create API Key" button. Copy the API key and paste it into your project's `.env` file. --- ## Behavior Most simply put, Prod API keys persist translations, while Dev API keys do not. You use Dev API keys for prototyping translations and Prod API keys when you are ready to deploy. ### Development API Key This type of key is useful for testing and development purposes. When using a development API key, translations are done on-demand and memoized in memory. Translations **will not be saved**. The development API key is used by components rendered in the browser (client-side) and by server-side rendered components to facilitate on-demand translation. This means that it must be exported to the client. This key should NEVER be used in production environments and NEVER should be passed to the client in a production environment. ```bash # example Vite .env file for dev VITE_GT_PROJECT_ID=your-project-id VITE_GT_API_KEY=your-dev-api-key # Only used in development ``` **Warning:** Development API keys are passed to the client to facilitate client-side translation in development. This is fine in development environments, but is a security risk in production environments. If your application is open to the internet, you should never use a development API key. ### Production API Key When using a production API key, translations **are persisted**. This means that translations will be saved (either in a CDN or in your app's bundle) to be used at runtime. This key is used in two places: * The [`gtx-cli`](/docs/cli) tool. Check out the [docs](/docs/cli) for more information. * The `gt-next` library when translations occur at runtime in a production build (server-side only, not used by `gt-react`). * [``](/docs/next/api/components/tx) and [`tx()`](/docs/next/api/strings/tx) functions are used to translate content at runtime. The API key is only used by the server, and it should NEVER be exported to the client. ```bash GT_PROJECT_ID=your-project-id GT_API_KEY=your-prod-api-key # This key should never be exported to the client ``` --- ## Notes * Development API keys are used for testing and development purposes. It should only be used in development. * Production API keys are used for production purposes. ## Next steps * Check out how to use [the `` component](/docs/react/guides/jsx) to see live translations in development. * See the [usage guide](/docs/cli/reference/usage) for the cli tool. # General Translation Platform: Translation CDN URL: https://generaltranslation.com/en/docs/platform/cdn.mdx --- title: Translation CDN description: How to use the CDN to serve your translations --- This feature is currently only supported for apps using `gt-next` or `gt-react`. ## Overview When you translate your `gt-next` or `gt-react` app, we automatically serve your translations from our CDN. In production, `gt-next` and `gt-react` will lazy-load these translations from the CDN if your users request your app in a different language. This means that you can internationalize your app without having to worry about latency or bundle size for your users. With 300+ edge nodes around the world, our CDN ensures that your users will always experience the lowest latency possible when viewing your app in a different language. ## How to use By default, translations are automatically published to the CDN whenever you run `gtx-cli translate`. However, you can disable it if you need to. 1. Go to the [project settings page](https://dash.generaltranslation.com/settings/project). 2. Toggle the "Publish to CDN" switch. 3. Re-run the `gtx-cli translate` command. If you disable the CDN, make to that you've set up your app to use local translations. [gt-next](/docs/next/guides/local-tx) or [gt-react](/docs/react/guides/local-tx) # General Translation Platform: Project Context URL: https://generaltranslation.com/en/docs/platform/context.mdx --- title: Project Context description: How to add context to your project on the General Translation platform --- This feature is currently only supported for apps using `gt-next` or `gt-react`. Project context for file translation is not yet supported. ## Overview Project context allows you to provide additional information about your project to help improve the quality of your translations. We support the following context types: - Author - Project Description - Project Audience - Project Tone - Glossary ## How to add context 1. Go to the [AI context page](https://dash.generaltranslation.com/project/context). 2. Enable context for your project, if you haven't already. 3. Fill out the context fields. 4. Save your changes. ## How to add glossary terms 1. Go to the [AI context page](https://dash.generaltranslation.com/project/context). 2. Switch to the "Glossary" tab. 3. Click on "New Keyword" 4. Fill out the keyword and definition fields. 5. Save your changes. Glossary terms also support keyword translations. Simply switch the language in the dropdown menu and fill out the translation field. # General Translation Platform: Examples URL: https://generaltranslation.com/en/docs/platform/examples.mdx --- title: Examples description: Example projects using General Translation --- This is a list of example projects using General Translation. ## Next.js ### Create Next.js App - [Source](https://github.com/generaltranslation/gt/tree/main/examples/next-create-app) - [Demo](https://next-create-app-eight.vercel.app/) ### Next.js AI Chatbot - [Source](https://github.com/generaltranslation/gt/tree/main/examples/next-chatbot) - [Demo](https://example-ai-chatbot-ten.vercel.app/) ## React ### Create Vite App - [Source](https://github.com/generaltranslation/gt/tree/main/examples/vite-create-app) - [Demo](https://example-vite-create-app.vercel.app/) # General Translation Platform: FAQs URL: https://generaltranslation.com/en/docs/platform/faqs.mdx --- title: FAQs --- ## Technical FAQs ### Where does the `` get its translations? What translations does it use? `` can technically load translations from anywhere depending on how you've configured the library. If you have a project ID, the library can hit a free CDN. It can also store translations locally, or do a mix of the two. See the [load-translations docs](/docs/next/api/config/load-translations#fetching-translations-from-your-bundle) for more details. During development, so you can see the translations hot-reload when you change content, the `` component hits an API which uses a small AI model to create temporary translations. These translations aren't stored anywhere, they're just served back to the app. In production, `` won't do this in order to not leak your API keys. ### Why do I have to install the CLI tool? The CLI tool parses the content inside all `` components and generates translations for that content in advance, so that all the translations are ready when your app is deployed to production. In development, you don't need it because you can use development API keys to translate on demand. ### Is there an automatic fallback for missing translations in production? Yes, if in production, a translation for some content is missing, the library will automatically fallback to the original source text. ### Does the AI translation also work with dynamic content and variables? The `` component doesn't support translating dynamic content and variables, because this means the translations could potentially change with every re-render. However, you can still include dynamic content and variables inside a `` by wrapping them with ``, ``, `` components. This is similar to how other libraries do string interpolation. For gt-next, there is also a `` server-side component which does actually do translations on the spot in production, and supports any form of dynamic content, but it requires an API key. ### How does the offline system work? Can I deploy an application with GT without dependency on your servers? Yes you can, but you'd have to do the translations yourself, then load them either from your own bundle or your own CDN. See our docs on that: [here](/docs/next/api/config/load-translations#fetching-translations-from-your-bundle). ## Business FAQs ### Do I own my translations? **Yes.** > You, the customer, retain full ownership and rights to any translated output produced through the Services. We make no claim to your output. For more, see our [Terms of Use](https://generaltranslation.com/terms). ## General FAQs ### What are tokens? When text is sent to [GT](https://www.generaltranslation.com) APIs, it is broken down into chunks called *tokens*. Think of tokens as small pieces of your input text, like words or parts of words, that an AI model uses to understand and translate your content. > A helpful rule of thumb is that one token generally corresponds to ~4 characters of text for common English text. This translates to roughly ¾ of a word (so 100 tokens ~= 75 words). For example, the string `Hello, world!` has 13 characters, and 4 tokens: `Hello`, `,`, ` world`, and `!`. If you go over the token limit for your plan, we begin to charge based on token usage. We only ever charge based on the length of your input — never the length of the translation. Read more about our available plans [here](https://generaltranslation.com/pricing). For example, imagine you have the string `"Hello, world!"`, and your project's languages are `"fr"` (French), `"es"` (Spanish), and "`de"` (German). Token usage will be calculated as `4 * 3 = 12`. That is, the 4 tokens of `"Hello, world!"`, translated 3 times. We currently tokenize with OpenAI's `tiktoken`, which is the same tokenizer used by [GPT-4](https://openai.com/index/gpt-4/). You can explore this tokenizer [here](https://platform.openai.com/tokenizer). ### Locales? Languages? Regions? What's the difference? Throughout this documentation, you will see us use the term *locale* and *language* somewhat interchangeably. For the most part, they do mean the same thing, but there are some subtle differences, and these will be made clear when necessary. *Language* refers to a spoken or written form of communication used by humans. *Region* refers to the area where a language is spoken or written. Of course, the language may remain the same, but vary between regions. For example, Canadian French versus French as spoken in France. *Locale* is a combination of a language and a region, and is used to specify a particular language in a particular region. For example, `en-US` is English as spoken in the United States. These differences are detailed further in our documentation on [Locale Strings](/docs/platform/locale-strings). # General Translation Platform: Quickstart URL: https://generaltranslation.com/en/docs/platform.mdx --- title: Quickstart description: Docs for General Translation's localization libraries --- ## Getting started Click on your React framework to get started: Alternatively, you can run the [Setup Wizard](/docs/cli/init). ```bash npx gtx-cli@latest ``` ## What is General Translation? General Translation is an entire internationalization (i18n) stack that allows you to ship multilingual apps quickly and easily. ![Live translations in action](/live_translations.gif) General Translation includes the following: - Open-source developer libraries for React and Next.js - An AI translation service - A complete infrastructure package for serving translation content If you would like to use GT libraries with your own translation provider, please see our standalone docs for [gt-next](/docs/next/concepts/stand-alone) and [gt-react](/docs/react/concepts/stand-alone). If you would like to use your own i18n library, but still want to use General Translation's AI translation service, please see our [CLI tool](/docs/cli) docs. If you would like to use General Translation to translate your JSON, Markdown, or MDX files, please see our [CLI tool](/docs/cli) docs. ```bash npx gtx-cli@latest init ``` Run our setup wizard to get started! ## Features ### ⚛️ Translate entire React components in-line - A single opening and closing `` component is all you need to translate an entire React component. - No need for complex refactoring or messy function calls. - Content is in-line and in the same location as your code. - No keys, strings, or additional files are needed! - The library manages all i18n logic behind the scenes, so you don't have to. - Translations are always kept in sync with your source code. - Translations contain contextual information about the content, so they are more accurate. ```jsx title="Page.jsx" copy export default function Page() { return ( // [!code highlight]

You can write any JSX as children of the {""} component.

For example, you could write a link and have the text be translated in context.

Even deeply nested components are translated in context.

// [!code highlight] ); } ``` ### 🔎 Feature parity with existing libraries - GT libraries also support the same features as existing libraries like `i18next`, `react-intl`, and `next-intl`. - Features such as dictionaries, plurals, currencies, and automatic routing are all supported. ### 🧠 Free AI-powered translation service - Our free AI-powered translation service allows you to create translations for your app in seconds. - **Translation hot reload** will automatically update your translations as you write them. - HTML content is re-arranged and customized according to the language. ### 🔧 Developer-friendly - Setup is simple and can be done in minutes. - All GT libraries are open-source and work standalone. - You can use your own translation provider or use our free AI-powered translation service. - No more wasting time managing translation keys like `t('menu.header.title')`. - Just write everything in-line! See our [Github repo](https://github.com/generaltranslation/gt) for the source code and some example projects. These docs are under construction. Please create an issue on our [GitHub repository](https://github.com/generaltranslation/gt/issues) if what you're looking for isn't here. --- ## Why choose General Translation? **General Translation is an entire i18n stack**, including developer libraries, AI translations, and a complete infrastructure package for multilingual apps. You can mix and match our libraries with your own translation provider, or use our free AI-powered translation service with your own i18n library. For a seamless, end-to-end i18n experience, we recommend using our libraries with our translation service. With GT libraries like `gt-react` and `gt-next`, you can: ### 1. Translate entire React components, not just strings UI passed as the children of the `` component will be translated regardless of how complicated the JSX tree is. For example: ```javascript title="page.jsx" import { T } from "gt-next"; export default function Page() { return ( // [!code highlight]

Any children of the {``} component will be translated.

Things like links{', '} {', '} and even

deeply nested components
are translated.

// [!code highlight] ); } ``` ### 2. Translate both client and server components With first class support for the Next.js [App Router](https://nextjs.org/docs/app) and [React Server Components](https://react.dev/reference/rsc/server-components), you can translate both client and server components. ```jsx title="src/components/MyServerComponent.jsx" copy import getName from "@/getName"; import { T, Var } from "gt-next"; export default async function MyServerComponent() { const name = await getName(); return ( {/* [!code highlight] */} Hello, {name} ); } ``` ```jsx title="src/components/MyClientComponent.jsx" copy "use client"; import { useState } from "react"; import { T, Var } from "gt-next"; export default function MyClientComponent() { const [name, setName] = useState("Alice"); return ( {/* [!code highlight] */} Hello, {name} ); } ``` ### 3. Write content inline or in dictionaries JSX content placed inside a `` component is marked for translation: ```jsx title="Page.jsx" copy import { T } from "gt-next"; export default function Page() { return ( {/* [!code highlight] */}

Hello, World!

{/* translates

Hello, World!

*/}
) } ``` Alternatively, if you prefer using the historic dictionary approach, you can write your content in a dictionary file: ```json title="dictionary.json" copy { "greeting": "Hello, World!" } ``` ```js title="dictionary.js" copy const dictionary = { greeting: "Hello, World!" } export default dictionary; ``` ```ts title="dictionary.ts" copy const dictionary = { greeting: "Hello, World!" } export default dictionary; ``` ```jsx title="page.jsx" copy import { useDict } from "gt-next"; export default function Page() { const d = useDict(); return d('greeting'); // translates "Hello, World!" // [!code highlight] } ``` ### 4. View translated content in development No need to worry about how UI looks in different languages, **General Translation will automatically translate your content as you write it in real-time.** Instead of having to continuously revise your UI multiple times in production, simply write your content in English **once** and let General Translation handle the rest. Need to see how your UI elements look in German before deploying? No problem, General Translation will automatically translate them for you! ### 5. Translate content on-demand Apps often need to translate content only known at runtime. For Next.js, GT libraries support the ability to translate content on demand. Some common examples include: - User-specific information - Remotely stored content - Content that is generated dynamically Once the translation is loaded, it will rewrite your component in real time with the new translation content. ## Get started Follow the [Quickstart](/docs/next/tutorials/quickstart) guide to ship your first translations. ```bash npm i gt-next ``` ```bash yarn add gt-next ``` ```bash bun add gt-next ``` ```bash pnpm add gt-next ``` Follow the [Quickstart](/docs/react/tutorials/quickstart) guide to ship your first translations. ```bash npm i gt-react ``` ```bash yarn add gt-react ``` ```bash bun add gt-react ``` ```bash pnpm add gt-react ``` Ready to go global? Start translating your app in minutes and reach users worldwide! # General Translation Platform: Locales URL: https://generaltranslation.com/en/docs/platform/locale-strings.mdx --- title: Locales description: Locales and Locale Strings --- ## Overview This page will discuss the standard used by General Translation to represent locales & languages and the list of currently supported locales. --- ## Locale strings General Translation uses a variant of the [BCP 47 Language Tag standard](https://www.techonthenet.com/js/language_tags.php) to represent locales and languages. BCP 47 Language Tags are the Internet Best Current Practices (BCP) standard for identifying languages in both spoken and written forms. These tags provide a uniform way to specify languages, allowing applications to adapt content, format, and behavior based on the user's locale. Language tags are composed of one or more subtags separated by the `"-"` character. The subtags include the following components: - **Language Subtag**: Represents the primary language, e.g., `en` for English, `es` for Spanish. - **Region Subtag**: Specifies a country or region, e.g., `US` for the United States, `FR` for France. - **Script Subtag** (optional): Indicates the writing script, e.g., `Latn` for Latin script. - **Variant Subtag** (optional): Identifies a specific variation of a language, e.g., `arevela` for Eastern Armenian. When you combine these tags together, we refer to this as a **Locale** or **Locale tag**. ### Commonly Used Tags In practice, most language tags consist of two subtags: a language and a region. Here are some common examples: | Language Tag | Description | |--------------|----------------------------| | `en-US` | English as used in the US | | `es-ES` | Spanish as used in Spain | | `fr-CA` | French as used in Canada | | `zh-CN` | Simplified Chinese (China) | | `de-DE` | German as used in Germany | ### Extended Tags Language tags can include additional subtags for more specificity: - **Example**: `hy-Latn-IT-arevela` - `hy`: Armenian (language) - `Latn`: Latin (script) - `IT`: Italy (region) - `arevela`: Eastern Armenian (variant) This tag represents Eastern Armenian written in Latin script, as used in Italy. ## Exceptions to BCP 47 in GT 🚧 This section is currently under construction. 🚧 --- ## Supported locales [#supported-locales] This section lists all locales that are currently supported by General Translation. ### A note on low-resource languages Our system leverages some of the most advanced LLM models on the market to provide accurate translations; however, these models are not without their limitations. Certain resource languages may not be supported by the model provider you have selected or any of the available providers. These languages are known as "low-resource languages". Low-resource languages can vary between models, so if you specify a preferred model provider in your configuration, you may want to check the list of supported languages for that provider. ### Official list --- ## Notes * General Translations uses **Locale Tags (Locales)** to identify languages and regions internally. ## Next Steps * See our [List of Supported Locales](/docs/platform/locale-strings#supported-locales) to find the language tags available in General Translation. * Refer to the official [IETF Language Tag Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry) and the [BCP 47 Language Tag standard](https://www.techonthenet.com/js/language_tags.php) for more information. # General Translation Platform: Open Source URL: https://generaltranslation.com/en/docs/platform/open-source.mdx --- title: Open Source description: General Translation libraries are open source! --- ## Overview All of our libraries are open source and free to use. They work fully standalone, out of the box. You can use them in any project, without needing to ever create an account or sign up for General Translation services. Standalone, our libraries support the following features: - Wrapping entire React components for translation - Dictionaries - Easy project setup - Middleware Using General Translation as a translation provider will unlock the following features: - On-demand translation - Automatic AI translations for React & Next.js, as well as many other file formats. - A no-hassle translation CDN ## How to use To use `gt-next` or `gt-react` with your own translation provider, see the docs on using local translations: ## Managing translations To generate the translation files for your project, run the CLI tool with the following command: ```bash npx gtx-cli configure # Configure your project npx gtx-cli generate # Generate the translation files ``` This command will generate the JSON data files for your project's source code. You can then use these files with your own translation provider. To load the translations into `gt-next` or `gt-react`, use the `loadTranslations` function, as specified in the local translations guide. See the [CLI API reference](/docs/cli/generate) for more information. # General Translation Platform: Pricing URL: https://generaltranslation.com/en/docs/platform/pricing.mdx --- title: Pricing description: Pricing details about the General Translation platform --- All of our features are free to use. There are 3 ways to use General Translation: 1. Free Tier: Use our open-source libraries with our free AI-powered translation service. 2. Paid Tier: Use our open-source libraries with our paid translation service. 3. Fully standalone: Use our open-source libraries with your own translation provider. ## Free Tier General Translation offers a generous free tier for our AI-powered translation service. This free tier is rate-limited on a per-organization basis to: - 20,000 production tokens per month. - 30,000 development tokens per month. This tier is intended for personal use on small solo projects. ## Paid Tiers If you're working on a larger project and need more tokens, you can upgrade to a paid plan. Our paid plans are pay-as-you-go, with an included quota of tokens every billing cycle. We currently offer 2 paid plans: - **Pro** - **Enterprise** ### Pro The Pro plan includes $30 worth of tokens every month (paid monthly), or $360 worth of tokens every year (paid yearly). Our token rates are priced at: - $0.0005 per token translated in production. - $0.0001 per token translated in development. The type of API key used determines the type of token you'll be billed for. See the [API keys](/docs/platform/apikeys) page for more information on the different types of API keys. We use the [OpenAI Tokenizer](https://platform.openai.com/tokenizer) to calculate tokens from a text corpus. ### Enterprise Please [contact us](https://generaltranslation.com/contact) for more information on the Enterprise plan. ## Fully standalone If you like the features offered by the General Translation libraries, such as `` components and `useGT()` functions, but don't want to use our translation service, you can use our libraries with your own translation provider. This will require more manual work, but you will have full control over your translations. See the [open-source docs](/docs/platform/open-source) for more information. # General Translation Platform: Reviewing Translations URL: https://generaltranslation.com/en/docs/platform/review.mdx --- title: Reviewing Translations description: How to review translations on the General Translation platform --- This feature is currently only supported for apps using `gt-next` or `gt-react`. ## Overview After you've translated your project with General Translation, you can review your translations on the General Translation platform before they go live. This feature is useful for: - Catching any issues with your translations before they go live. - Compliance with your organization's internal content policies. - Compliance with legal and regulatory requirements. ## How to use This feature is currently only available to organizations with a paid plan. To enable human review, you need to: 1. Go to the [project settings page](https://dash.generaltranslation.com/settings/project). 2. Toggle the "Human Review" switch. In your CI pipeline, instead of running `gtx-cli translate`, run [`gtx-cli stage`](/docs/cli/commands/stage) to stage your translations for review. Then, when you're ready to deploy your app in CD, run `gtx-cli translate` Think of `stage` as `git add + git commit` for translations, while `translate` is `git push`. `stage` simply stages your translations for review, while `translate` completes the process and downloads the translations (if configured to do so). `stage` must always be ran before `translate`, just like how `git add & commit` must always be ran before `git push`. ## How to review translations 1. Go to the [project review page](https://dash.generaltranslation.com/project/review-translations). 2. Select the language you want to review. 3. Go through each translation for that language and approve it. If you're not happy with a translation, you can edit it or request a new translation. 4. Or, click the "Approve All" button to approve all translations for the language. Until all translations for a language are approved, the CLI tool will hang (when running `gtx-cli translate`), and no translations will be published to the CDN. When all translations for a language are approved, the translation will automatically be published to the CDN (if enabled). Currently, file approval is not supported. Only Jsx approval is currently supported. # General Translation Platform: Custom Roles URL: https://generaltranslation.com/en/docs/platform/roles.mdx --- title: Custom Roles description: Custom roles on the General Translation platform --- ## Overview For organizations on Pro or Enterprise plans, you can invite users to your organization and assign them custom roles. This is useful for: - Sharing access to the platform with your developers. - Inviting outside collaborators to review translations. - Assigning specific permissions to users. ## How to invite users 1. Go to the [organization members page](https://dash.generaltranslation.com/org/members). 2. Click the "Invite Users" button. 3. Enter the email address of the user you want to invite. ## How to manage roles 1. Go to the [organization members page](https://dash.generaltranslation.com/org/members). 2. Click the "..." options button next to the user you want to manage. 3. Click the "Manage Roles" button. 4. Toggle the roles you want the user to have. 5. Click the "Save" button. ## How to remove users 1. Go to the [organization members page](https://dash.generaltranslation.com/org/members). 2. Click the "..." options button next to the user you want to remove. 3. Click the "Remove User" button. # General Translation Platform: Terminology URL: https://generaltranslation.com/en/docs/platform/terminology.mdx --- title: Terminology description: A guide to the key terminology used in the General Translation libraries --- ## Overview Throughtout these docs, we use a variety of terminology to describe the different concepts used in the General Translation libraries. This page highlights some of the key terminology we use. ## Key Terminology ### Locale A locale is a code used to identify a specific language. See the [locale strings](/docs/platform/locale-strings) page for a more detailed explanation. For example, `en-US` is the locale for English (United States). Throughout these docs, we often use the term "locale" and "language code" interchangeably. ### Language When we refer to a language in the context of using it with code, we actually mean the locale. (Or the language code) For example, when we say "provide the language in the call to `setLocale`", we actually mean "provide the locale in the call to `setLocale`". If we say "French is a supported language", we actually mean "`fr` is a supported locale". ### Dictionary A dictionary is a JSON file that contains a set of (potentially nested) key-value pairs. The keys are used as references, and the values are strings, either in the original language or in a translated language. ```json { "greeting": "Hello, World!", "farewell": "Goodbye, World!", "dashboard": { "title": "Dashboard", "description": "Welcome to the dashboard" } } ``` The keys are human-readable references which are used to look up the translated content within your app. These dictionaries are conventional in structure and usage, similar to translation files in other i18n libraries. A source dictionary can also be a `.js` or `.ts` file, meaning it can import from other files. A dictionary containing translated content can only be a `.json` file. #### Source Dictionary A source dictionary is a dictionary that contains content in the default locale for your app. #### Translated Dictionary A translated dictionary is a dictionary that contains content in a specific locale that is different from the default locale. The keys are the same as the source dictionary, and the values are the translated strings. If you have your own translated dictionaries, you can load them using the `loadDictionary()` function. ### In-line content In-line content is content that is written directly in your app's code, and not stored separately in something like a JSON or dictionary file. This includes: - `` components - `useGT` hooks - `getGT` function ### Source Content Source content is the content in the default locale for your app. It includes anything written in your app's default language. Specifically for `gt-next`, and `gt-react`, source content includes all of the translatable content for your app, including your app's source dictionary and any in-line content. ### Source Template Source template refers to the specific data format for storing source content. ```json { ["Unique identifier for the source content"]: "...Content..." } ``` The unique identifier for the source content is either a hash of the source content, or a user-defined unique identifier. Depending on the type of the source content, the corresponding value can be a string, array, or an object. (Strings and arrays for dictionaries, and objects for `` components) ### Translations Throughout these docs, we use the noun "translations" to refer to the translated content obtained from translating source content. Translations are generated directly from your source template. The `loadTranslations()` function allows you to customize the location where these translations are stored. This function expects the JSONs to be of the same format as the source template. Use the [CLI `generate` command](/docs/cli/generate) to generate these data files from your source content. **Note:** It's important to note that a translation is _different_ from a translated dictionary. Dictionaries are potentially nested, and contain human-readable references as keys. Translations, on the other hand, are flat, and likely contain non-human-readable hashes as keys. **Translations** are what is stored on the GT CDN. If we use translations in reference to JSON, MDX, or MD files, we are referring to the direct translations of the original source files. # gt-react: General Translation React SDK: Quickstart URL: https://generaltranslation.com/en/docs/react.mdx --- title: Quickstart description: Easily internationalize your React App with gt-react --- ## Overview This quickstart guide will walk you through internationalizing your React app with `gt-react`. By the end of this guide, you will have a fully internationalized React app. In this guide, we will cover the following: Installation Configuration Usage Testing Your App Deployment ### Prerequisites - A React project using a supported framework (Next.js, Vite, etc.) - Basic knowledge of React and JavaScript ## Installation Install the `gt-react` and `gtx-cli` packages: ```bash npm i gt-react npm i --save-dev gtx-cli ``` ```bash yarn add gt-react yarn add --dev gtx-cli ``` ```bash bun add gt-react bun add --dev gtx-cli ``` ```bash pnpm add gt-react pnpm add --save-dev gtx-cli ``` --- **Automatic Setup:** We have an experimental Setup Wizard that can help you setup your project with `gt-react`. Try it out by running `npx gtx-cli@latest`. You'll still need to manually internationalize strings, but it will help you get started. See the [Setup Wizard](/docs/cli/init) reference guide for more information. Alternatively, if you would like your AI tool like Claude Code, Cursor, or Windsurf to automatically setup your project, you can use our [mcp server](/docs/platform/ai-tools). ## Configuration ### `GTProvider` The core of `gt-react` is the `GTProvider` component. It is responsible for: - Managing the user's current locale - Providing relevant translations to your application - Providing context to hooks for accessing translations - Providing context to hooks for changing the user's locale First, add the `GTProvider` component to your application. It should be placed as high up in your component tree as possible. ```tsx copy title="src/App.tsx" import { GTProvider } from 'gt-react'; export default function App() { return ( ); } ``` Next, create a [`gt.config.json`](/docs/react/api/config/gt-config-json) file in the root of your project. This file is used to configure both the `gtx-cli` tool and the `gt-react` library. ```json title="gt.config.json" copy { "defaultLocale": "en", "locales": ["fr", "es"] } ``` You should customize the `defaultLocale` and `locales` to match your project. See the list of [supported locales](/docs/platform/locale-strings) for more information. Lastly, spread the `gt.config.json` file into the provider's props. ```tsx import gtConfig from './gt.config.json'; ``` Spreading the `gt.config.json` file makes the config consistent across your application and CLI tool. Alternatively, you can individually specify each prop in the `GTProvider` component. ```tsx ``` ### Environment Variables Set the following environment variables: ```bash copy VITE_GT_API_KEY="" # Your General Translation Developer API key VITE_GT_PROJECT_ID="" # Your General Translation project ID ``` ```bash copy GATSBY_GT_API_KEY="" # Your General Translation Developer API key GATSBY_GT_PROJECT_ID="" # Your General Translation project ID ``` ```bash copy REDWOOD_ENV_GT_API_KEY="" # Your General Translation Developer API key REDWOOD_ENV_PROJECT_ID="" # Your General Translation project ID ``` ```bash copy NEXT_PUBLIC_GT_API_KEY="" # Your General Translation Developer API key NEXT_PUBLIC_GT_PROJECT_ID="" # Your General Translation project ID ``` ```bash copy REACT_APP_GT_API_KEY="" # Your General Translation Developer API key REACT_APP_GT_PROJECT_ID="" # Your General Translation project ID ``` Many react frameworks each have a unique way of exporting environment variables to the client. In development environments, both `GT_API_KEY` and `GT_PROJECT_ID` need to be exported to the client. We have added support for a few libraries so far, but please let us know if your framework is not listed by creating an issue on our [GitHub repository](https://github.com/generaltranslation/gt/issues/new). **Make sure your API key variable is only set in your development environment! It should not be set in production.** You can get a free API key and project ID by creating a [General Translation account](https://dash.generaltranslation.com/signup). After creating an account, navigate to the [Development API Keys](https://dash.generaltranslation.com/settings/dev-api-keys) page to get your Dev API key and project ID. Alternatively, you can also use the CLI tool command [`npx gtx-cli auth`](/docs/cli/auth) to generate an API key and project ID for your project, saved to your `.env.local` file. `gt-react` is an i18n library that can work standalone without any environment variables. Without them, the library will act very similarly to other i18n libraries, and will still have core internationalization functionality. However, `gt-react` also offers a native integration with the General Translation platform. This integration unlocks additional functionality in the library, such as: - Translation Hot Reloading in Development - Automatic AI translations - Syncing translations with the General Translation platform - Native integration with our translation CDN To avoid using the General Translation platform, just don't set any environment variables. --- ## Usage Great! If you've followed the steps above, your React project is now setup to use `gt-react`. The next step is to internationalize your content. Here, we'll give a brief overview of the different ways to translate content in your application. ### `` Component The `` component is the main component for translating JSX content in your application. To use it, simply wrap the JSX you want to translate in the `` component. ```tsx import { T } from 'gt-react';
Your content
``` If you have dynamic content, you'll need to use [variable components](/docs/react/guides/variables) to pass in the dynamic values. ```tsx import { T, Var } from 'gt-react';
Hello, {name}!
``` See the [Translating JSX](/docs/react/guides/jsx) guide for more information. ### `useGT` Hook The `useGT` hook is a React hook that returns a function that can be used to translate strings. ```tsx import { useGT } from 'gt-react'; const translate = useGT(); translate('Hello, world!'); ``` See the [Translating Strings](/docs/react/guides/strings) guide for more information. Utilizing the hot-reload translation functionality will be helpful for internationalizing your application. To enable this, make sure you have the `GT_API_KEY` and `GT_PROJECT_ID` environment variables set in your development environment. --- ## Testing Your App Congratulations! 🥳 If you've followed the steps above, your app is now multilingual! Let's see it in action. ### See Your App in a Different Language Add the [``](/docs/react/api/components/localeSelector) component to your app. This will allow you to select a different language for your app. **Tip:** You can also skip this step and just change your language in your browser settings. Start your React app in development mode. ```bash npm run dev ``` ```bash yarn run dev ``` ```bash bun run dev ``` ```bash pnpm run dev ``` Open up your app in your preferred browser (usually at [http://localhost:3000](http://localhost:3000)). ### Troubleshooting **Browser Cookies** If you are deciding to test different languages by changing your browser's language, this issue may occur. Check your browser's cookies for your app. General translation uses cookies to store the user's language preference. The cookie is called `generaltranslation.locale`, and all you need to do is delete it. Then, just double check you are using the desired perferred language and then refresh the page. How to check cookies: * [Chrome](https://support.google.com/chrome/answer/95647) * [Firefox](https://support.mozilla.org/en-US/kb/delete-cookies-remove-info-websites-stored) * [Safari](https://support.apple.com/en-mn/guide/safari/sfri11471/16.0/mac/11.0) * [Edge](https://support.microsoft.com/en-us/microsoft-edge/delete-cookies-in-microsoft-edge-63947406-40ac-c3b8-57b9-2a946a29ae09) If this does not work, make sure that the list of locales in your [``](/docs/react/api/components/gtprovider) is up to date. **On-Demand Translation** You may notice when loading languages in development, translations will take a few seconds to be displayed. This happens because your app is being translated in real time. We refer to this process as an "on-demand translation". This **only happens in dev** so you can easily prototype your website in different languages. All translations are preloaded in production, so there will be no delay. Follow our guide on [shipping to production](/docs/next/tutorials/quickdeploy). **JSX Translation** Right now, the setup tool automatically adds `` components around text content. We are currently working on a solution that will automatically setup string translations. Until then, if you are rendering a string, please follow [this guide](/docs/react/guides/strings) for translating strings. The most likely cause of an inaccurate translation is ambiguous wording. For example, "apple" can be a fruit or a technology company. To fix this, you can provide more context to the translation with the `context` prop. The [``](/docs/react/api/components/t) and [`useGT()`](/docs/react/api/strings/useGT) functions support a `context` prop. For example: ```jsx Apple ``` See our [guide on the `` component](/docs/react/guides/jsx) for more information. --- ## Deployment Great! If you're satisfied with your translations and the functionality of your app, you can now deploy your application. The behavior of `gt-react` in production is slightly different from development. Specifically, no translations will be performed at runtime. This means that you'll need to translate your content before deploying your application, in the build process. Luckily, the `gtx-cli` tool has a `translate` command that can be used to automatically translate your content. First, you'll need to get a Production API key from the [General Translation platform](https://dash.generaltranslation.com). Please note that this key is different from your Development API key, and begins with `gtx-api-`, instead of `gtx-dev-`. Read about the difference between Development and Production keys [here](/docs/react/concepts/environments). Add this environment variable to your CI/CD pipeline. ```bash GT_PROJECT_ID= GT_API_KEY= ``` Make sure that `GT_API_KEY` is **NOT** prefixed with `NEXT_PUBLIC_` or `VITE_`, depending on your framework! If it is, you'll risk exposing your API key to the public. Run the `translate` command to translate your content. ```bash npx gtx-cli translate ``` You can configure the behavior of the `translate` command with the [`gt.config.json`](/docs/cli/reference/config) file. See the [CLI Tool](/docs/cli/translate) reference guide for more information. Add the `translate` command to your build process. ```json title="package.json" copy { "scripts": { "build": "npx gtx-cli translate && <...YOUR_BUILD_COMMAND...>" } } ``` If you're not using the General Translation platform, you can still use `gt-react` in production. However, you'll need to manually translate your content before deploying your application. Instead of running `translate`, run the `generate` command to generate JSON files containing all of your translation data (in your source language). ```bash npx gtx-cli generate ``` Then, you'll need to manually edit / translate these files, and load them into your application with [`loadTranslations`](/docs/react/guides/local-tx). --- ## Summary * In this guide, we covered how to setup your React project with `gt-react` * We briefly covered the different ways to translate content in your application. * We also covered how to deploy your application after you've internationalized your content. ## Next Steps - Learn about how to translate JSX content with the `` component: [Translating JSX](/docs/react/guides/jsx) - Learn about how to translate strings with the `useGT` hook: [Translating Strings](/docs/react/guides/hooks) - Learn how to use local translations: [Local Translations](/docs/react/guides/local-tx) # gt-react: General Translation React SDK: Overview URL: https://generaltranslation.com/en/docs/react/introduction.mdx --- title: Overview description: Overview of General Translation's React SDK --- ## Introduction The General Translation React SDK is an open-source internationalization (i18n) library for React. It offers a set of tools to help you internationalize your React application in a easy and maintainable way, with feature parity to other popular i18n libraries. The React SDK can be used without the General Translation platform, and will act very similarly to other i18n libraries. However, it also integrates with our platform, offering additional features such as: - Translation Hot Reloading in Development - Automatic AI translations - Syncing translations with the General Translation platform - Native integration with our translation CDN ## Concepts There are 4 main concepts to understand about the SDK. The `` component The `` component The `useGT` hook (Optional) The `useDict` hook ## The `` component ```tsx import { GTProvider } from 'gt-react'; ``` The `` component is the main component that you need to add to your application. It is used to provide the rest of your application with context. This context includes the current language and the relevant translations for that language. ### Important Considerations - The provider should wrap your entire application. - Ideally, it should be placed as high in the tree as possible, such as in your root component. See the [GTProvider](/docs/react/api/components/gtprovider) page for more information. ## The `` component The `` component is the recommended way to translate content in your application. It is a React component that can be used to wrap any JSX element, and will automatically render the content of the element into a supported language. We recommend using the `` component wherever possible, since it allows for the most flexibility in translations. Unlike strings, the `` component can be used to translate HTML content, making it much more powerful than string translations. ### Examples ```tsx
Hello, world!
``` ```tsx

Here is an image

Example
``` ```tsx Formatting can be done easily with the `` component. {1000} {new Date()} {1000} ``` See the [translating JSX](/docs/react/guides/jsx) guide to learn about the different ways to use the `` component. See the [T API Reference](/docs/react/api/components/t) for the API of the `` component. ## The `useGT` hook The `useGT` hook is a React hook that can be used similarly to the `` component, with some trade-offs. The hook returns a function that can be used to translate strings. ```tsx const translate = useGT(); translate('Hello, world!'); ``` Compared to the `` component, the `useGT` hook allows for more flexibility in your codebase. For example, if you have a complex data structure with nested strings, a `` component would be more difficult to use. ```tsx const t = useGT(); const data = { title: t('Hello, world!'), description: t('This is a description'), }; ``` See the [strings](/docs/react/guides/strings) guide to learn more about the `useGT` hook. See the [useGT API Reference](/docs/react/api/strings/useGT) for more information. ## The `useDict` hook The `useDict` hook is a React hook that returns a function that can be used to retrieve translations for a given key. ```tsx title="dictionary.ts" const dictionary = { hello: { world: 'Hello, world!', }, }; ``` ```tsx title="App.tsx" const translate = useDict(); translate('hello.world'); ``` This behavior is similar to other translation libraries, such as `react-i18next` and `next-intl`. We do not recommend using the `useDict` hook in your application. Frequent use of the `useDict` hook will make your codebase more difficult to maintain, and will lead to large tech debt. Instead, we recommend using the `` component or the `useGT` hook. If you are migrating from another i18n library, the `useDict` hook is a drop-in replacement and can useful for incrementally migrating your codebase. See the [dictionaries](/docs/react/guides/dictionaries) guide to learn more about the `useDict` hook. See the [useDict API Reference](/docs/react/api/dictionary/useDict) for more information. --- ## Next Steps - Learn about how to setup your React project with the SDK: [Project Quickstart](/docs/react) - Learn about how to translate strings with the `useGT` hook: [Translating Strings](/docs/react/guides/hooks) - Learn about how to translate JSX content with the `` component: [Translating JSX](/docs/react/guides/jsx) # gtx-cli: General Translation CLI tool: gt-next & gt-react URL: https://generaltranslation.com/en/docs/cli/formats/gt.mdx --- title: gt-next & gt-react description: Automatically translate your gt-next or gt-react project --- ## Overview This tutorial will show you how to automatically manage your project's translation files when using [`gt-next`](/docs/next) or [`gt-react`](/docs/react). **Note:** This should only be used when you are shipping a production build. If you are using gt-next or gt-react in development, this command is not needed. We will follow these 4 steps: Add your environment variables Configure your project with the [`npx gtx-cli configure`](/docs/cli/configure) command Run [`gtx-cli translate`](/docs/cli/translate#translate-json) **Tip:** Avoid the hassle of using translation files with the [`` component](/docs/react/guides/jsx). --- ## Step 1: Add your environment variables Add your production API key and project ID to your environment variables. This is necessary to use the `gtx-cli` tool. You get these from the [General Translation dashboard](https://generaltranslation.com/dashboard). ```bash title=".env" GT_API_KEY= GT_PROJECT_ID= ``` ## Step 2: Configure your project with the `npx gtx-cli configure` command Run the `gtx-cli configure` command to configure your project. ```bash npx gtx-cli configure ``` ## Step 3: Add the `gtx-cli translate` command to your build process Add the `gtx-cli translate` command to your build or CI process before the build command to automatically add translations to your project. ```json title="package.json" { "scripts": { "translate": "npx gtx-cli translate", "build": "npm run translate && " } } ``` This will generate translations for all of your locales and save them to your project. If you want to commit these files to your repo, you can instead run this command before committing. You're done! Now your project will automatically update all of your translation JSON files any time your project changes. --- ## Notes * You can automatically add translations to your project with the [`gtx-cli translate`](/docs/cli/translate#translate-json) command. * If you want to commit your translation files, you can instead run the `gtx-cli translate` command before committing. * To configure the output path for your translations, see the [configuration](/docs/cli/reference/config) docs. ## Next steps * See the [usage guide](/docs/cli/reference/usage) for the cli tool. * If you want to see live translations in development (think hot reload), check out the [`` component](/docs/react/guides/jsx). # gtx-cli: General Translation CLI tool: i18next URL: https://generaltranslation.com/en/docs/cli/formats/i18next-quickstart.mdx --- title: i18next description: Automatically translate your i18next project (<5 min) --- ## Overview This tutorial will show you how to automatically manage your project's translation files if you are using [`i18next`](https://i18next.com/). We will follow these 4 steps: Add your environment variables Install [`gtx-cli`](/docs/cli) Create a `gt.config.json` file Run [`gtx-cli translate`](/docs/cli/translate#translate-json) **Tip:** Avoid the hassle of using translation files with the [`` component](/docs/react/guides/jsx). --- ## Step 1: Add your environment variables Add your production API key and project ID to your environment variables. This is necessary to use the `gtx-cli` tool. You get these from the [General Translation dashboard](https://generaltranslation.com/dashboard). ```bash title=".env" GT_API_KEY= GT_PROJECT_ID= ``` ## Step 2: Install `gtx-cli` Install the `gtx-cli` tool in your project. ```bash npm i --save-dev gtx-cli ``` ```bash yarn add --dev gtx-cli ``` ```bash bun add --dev gtx-cli ``` ```bash pnpm add --save-dev gtx-cli ``` ## Step 3: Create a `gt.config.json` file Create a `gt.config.json` file in the root of your project. ```json title="gt.config.json" copy { "defaultLocale": "en", "locales": ["zh", "es", "ja"], "files": { "json": { "include": ["messages/[locale]/*.json"] }, }, } ``` Feel free to customize the `gt.config.json` file to your needs. See the [configuration](/docs/cli/reference/config) docs for more information. Update the `json` file format such that the `include` path matches your project structure. Translations will preserve the original string syntax. ## Step 4: Add the `gtx-cli translate` command to your build process Add the `gtx-cli translate` command to your build or CI process before the build command to automatically add translations to your project. ```json title="package.json" { "scripts": { "translate": "npx gtx-cli translate", "build": "npm run translate && " } } ``` This will generate translations for all of your locales and save them to your project. If you want to commit these files to your repo, you can instead run this command before committing. You're done! Now your project will automatically update all of your translation JSON files any time your project changes. --- ## Notes * You can automatically add translations to your project with the [`gtx-cli translate`](/docs/cli/translate#translate-json) command. * If you want to commit your translation files, you can instead run the `gtx-cli translate` command before committing. * To configure the output path for your translations, see the [configuration](/docs/cli/reference/config) docs. ## Next steps * See the [usage guide](/docs/cli/reference/usage) for the cli tool. * Learn about how to migrate from `react-i18next` to `gt-next` with our [migration guide](/docs/react/guides/migration). # gtx-cli: General Translation CLI tool: JSON URL: https://generaltranslation.com/en/docs/cli/formats/json.mdx --- title: JSON description: How to automatically translate JSON files with General Translation --- ## Overview `gtx-cli` can be used to automatically translate your project's JSON files, regardless of what i18n library you are using. **Note:** We currently support custom string syntax and formatting for the following i18n libraries: [`next-intl`](/docs/cli/formats/next-intl-quickstart), [`i18next`](/docs/cli/formats/i18next-quickstart), [`gt-next`](/docs/cli/formats/gt), [`gt-react`](/docs/cli/formats/gt). If you are using a different i18n library, the translation results may not be accurate for strings with custom syntax and formatting (for example, ICU messages). Don't see your favorite library? [Please let us know](https://github.com/generaltranslation/gt/issues), and we will add it as soon as we can! We will follow these 4 steps: Add your environment variables Install [`gtx-cli`](/docs/cli) Create a `gt.config.json` file Run [`gtx-cli translate`](/docs/cli/translate#translate-json) **Tip:** Avoid the hassle of using translation files with the [`` component](/docs/react/guides/jsx). --- ## Step 1: Add your environment variables Add your production API key and project ID to your environment variables. This is necessary to use the `gtx-cli` tool. You get these from the [General Translation dashboard](https://generaltranslation.com/dashboard). ```bash title=".env" GT_API_KEY= GT_PROJECT_ID= ``` ## Step 2: Install `gtx-cli` Install the `gtx-cli` tool in your project. ```bash npm i --save-dev gtx-cli ``` ```bash yarn add --dev gtx-cli ``` ```bash bun add --dev gtx-cli ``` ```bash pnpm add --save-dev gtx-cli ``` ## Step 3: Create a `gt.config.json` file Create a `gt.config.json` file in the root of your project. ```json title="gt.config.json" copy { "defaultLocale": "en", "locales": ["zh", "es", "ja"], "files": { "json": { "include": ["i18n/[locale]/*.json"] }, }, } ``` Feel free to customize the `gt.config.json` file to your needs. See the [configuration](/docs/cli/reference/config) docs for more information. Update the `json` file format such that the `include` path matches your project structure. Translations will preserve the original string syntax. ## Step 4: Add the `gtx-cli translate` command to your build process Add the `gtx-cli translate` command to your build or CI process before the build command to automatically add translations to your project. ```json title="package.json" { "scripts": { "translate": "npx gtx-cli translate", "build": "npm run translate && " } } ``` This will generate translations for all of your locales and save them to your project. If you want to commit these files to your repo, you can instead run this command before committing. You're done! Now your project will automatically update all of your translation JSON files any time your project changes. --- ## Notes * You can automatically add translations to your project with the [`gtx-cli translate`](/docs/cli/translate#translate-json) command. * If you want to commit your translation files, you should run the `gtx-cli translate` command before committing. * To configure the output path for your translations, see the [configuration](/docs/cli/reference/config) docs. ## Next steps * See the [usage guide](/docs/cli/reference/usage) for the cli tool. # gtx-cli: General Translation CLI tool: Markdown URL: https://generaltranslation.com/en/docs/cli/formats/mdx.mdx --- title: Markdown description: How to use General Translation to set up automatic translation for your project's Markdown files --- ## Overview `gtx-cli` can be used to automatically translate your project's Markdown (MD and MDX) files. All syntax and formatting present in the original files will be preserved in the translated files. We will follow these 4 steps: Add your environment variables Install [`gtx-cli`](/docs/cli) Configure your project's [`gt.config.json`](/docs/cli/reference/config) file Run [`gtx-cli translate`](/docs/cli/translate#translate-mdx) --- ## Step 1: Add your environment variables Add your production API key and project ID to your environment variables. This is necessary to use the `gtx-cli` tool. You get these from the [General Translation dashboard](https://generaltranslation.com/dashboard). ```bash title=".env" GT_API_KEY= GT_PROJECT_ID= ``` ## Step 2: Install `gtx-cli` Install the `gtx-cli` tool in your project. ```bash npm i --save-dev gtx-cli ``` ```bash yarn add --dev gtx-cli ``` ```bash bun add --dev gtx-cli ``` ```bash pnpm add --save-dev gtx-cli ``` ## Step 3: Configure your project's `gt.config.json` file Create a `gt.config.json` file in the root of your project, with the following content: ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["es", "fr"], "files": { "mdx": { "include": ["docs/[locale]/**/*.mdx"] } } } ``` Change the `defaultLocale` and `locales` to match your project's locales. If your files are MD files, you can use the `md` key instead of `mdx`. The string array in the `include` key should be a glob pattern that matches all of your MDX files. It should use the `[locale]` placeholder to match the locale of the file. See the [configuration](/docs/cli/reference/config) docs for more information on the `gt.config.json` file. ## Step 4: Add the `gtx-cli translate` command to your build process Add the `gtx-cli translate` command to your build or CI process before the build command to automatically add translations to your project. ```json title="package.json" { "scripts": { "translate": "npx gtx-cli translate", "build": "npm run translate && " } } ``` This will generate translations for all of your locales and save them to your project. If you want to commit these files to your repo, you can instead run this command before committing. You're done! Now your project will automatically update all of your Markdown files any time your project changes. --- ## Notes - You can automatically add translations to your project with the [`gtx-cli translate`](/docs/cli/translate) command. - If you want to commit your translation files, you should run the `gtx-cli translate` command before committing. - To configure the output path for your translations, see the [configuration](/docs/cli/reference/config) docs. ## Next steps - See the [usage guide](/docs/cli/reference/usage) for the cli tool. # gtx-cli: General Translation CLI tool: next-intl URL: https://generaltranslation.com/en/docs/cli/formats/next-intl-quickstart.mdx --- title: next-intl description: Automatically translate your next-intl project in less than 5 minutes --- ## Overview This tutorial will show you how to automatically manage your project's translation files if you are using [`next-intl`](https://next-intl.dev/). We will follow these 4 steps: Add your environment variables Install [`gtx-cli`](/docs/cli) Create a `gt.config.json` file Run [`gtx-cli translate`](/docs/cli/translate#translate-json) **Tip:** Avoid the hassle of using translation files with the [`` component](/docs/react/guides/jsx). --- ## Step 1: Add your environment variables Add your production API key and project ID to your environment variables. This is necessary to use the `gtx-cli` tool. You get these from the [General Translation dashboard](https://generaltranslation.com/dashboard). ```bash title=".env" GT_API_KEY= GT_PROJECT_ID= ``` ## Step 2: Install `gtx-cli` Install the `gtx-cli` tool in your project. ```bash npm i --save-dev gtx-cli ``` ```bash yarn add --dev gtx-cli ``` ```bash bun add --dev gtx-cli ``` ```bash pnpm add --save-dev gtx-cli ``` ## Step 3: Create a `gt.config.json` file Create a `gt.config.json` file in the root of your project. ```json title="gt.config.json" copy { "defaultLocale": "en", "locales": ["zh", "es", "ja"], "files": { "json": { "include": ["i18n/[locale]/*.json"] }, }, } ``` Feel free to customize the `gt.config.json` file to your needs. See the [configuration](/docs/cli/reference/config) docs for more information. Update the `json` file format such that the `include` path matches your project structure. Translations will preserve the original string syntax. ## Step 4: Add the `gtx-cli translate` command to your build process Add the `gtx-cli translate` command to your build or CI process before the build command to automatically add translations to your project. ```json title="package.json" { "scripts": { "translate": "npx gtx-cli translate", "build": "npm run translate && " } } ``` This will generate translations for all of your locales and save them to your project. If you want to commit these files to your repo, you can instead run this command before committing. You're done! Now your project will automatically update all of your translation JSON files any time your project changes. --- ## Notes * You can automatically add translations to your project with the [`gtx-cli translate`](/docs/cli/translate#translate-json) command. * If you want to commit your translation files, you can instead run the `gtx-cli translate` command before committing. * To configure the output path for your translations, see the [configuration](/docs/cli/reference/config) docs. ## Next steps * See the [usage guide](/docs/cli/reference/usage) for the cli tool. * Learn about how to migrate from `next-intl` to `gt-next` with our [migration guide](/docs/next/guides/migration). # gtx-cli: General Translation CLI tool: TypeScript URL: https://generaltranslation.com/en/docs/cli/formats/ts.mdx --- title: TypeScript description: How to automatically translate TypeScript and JavaScript files with General Translation --- ## Overview `gtx-cli` can be used to automatically translate your project's JavaScript (js) and TypeScript (ts) files. All syntax and formatting present in the original files will be preserved in the translated files. We will follow these 4 steps: Add your environment variables Install [`gtx-cli`](/docs/cli) Configure your project's [`gt.config.json`](/docs/cli/reference/config) file Run [`gtx-cli translate`](/docs/cli/translate#translate-mdx) --- ## Step 1: Add your environment variables Add your production API key and project ID to your environment variables. This is necessary to use the `gtx-cli` tool. You get these from the [General Translation dashboard](https://generaltranslation.com/dashboard). ```bash title=".env" GT_API_KEY= GT_PROJECT_ID= ``` ## Step 2: Install `gtx-cli` Install the `gtx-cli` tool in your project. ```bash npm i --save-dev gtx-cli ``` ```bash yarn add --dev gtx-cli ``` ```bash bun add --dev gtx-cli ``` ```bash pnpm add --save-dev gtx-cli ``` ## Step 3: Configure your project's `gt.config.json` file Create a `gt.config.json` file in the root of your project, with the following content: ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["es", "fr"], "files": { "ts": { "include": ["docs/[locale]/**/*.ts"] } } } ``` Change the `defaultLocale` and `locales` to match your project's locales. If your files are JavaScript files, you can use the `js` key instead of `ts`. The string array in the `include` key should be a glob pattern that matches all of your JS files. It should use the `[locale]` placeholder to match the locale of the file. See the [configuration](/docs/cli/reference/config) docs for more information on the `gt.config.json` file. ## Step 4: Add the `gtx-cli translate` command to your build process Add the `gtx-cli translate` command to your build or CI process before the build command to automatically add translations to your project. ```json title="package.json" { "scripts": { "translate": "npx gtx-cli translate", "build": "npm run translate && " } } ``` This will generate translations for all of your locales and save them to your project. If you want to commit these files to your repo, you can instead run this command before committing. You're done! Now your project will automatically update all of your Markdown files any time your project changes. --- ## Notes - You can automatically add translations to your project with the [`gtx-cli translate`](/docs/cli/translate) command. - If you want to commit your translation files, you should run the `gtx-cli translate` command before committing. - To configure the output path for your translations, see the [configuration](/docs/cli/reference/config) docs. ## Next steps - See the [usage guide](/docs/cli/reference/usage) for the cli tool. # gtx-cli: General Translation CLI tool: Configuration URL: https://generaltranslation.com/en/docs/cli/reference/config.mdx --- title: Configuration description: Config docs for the gt.config.json file --- ## Overview The `gt.config.json` file is used to configure your project's GT settings. It should be placed in the root of your project. The CLI setup wizard [`npx gtx-cli init`](/docs/cli/init) will create a `gt.config.json` file for you in your project. ## Configuration The `gt.config.json` file accepts the following properties, but is not limited to them: - `defaultLocale`: The default locale for your project. This is the locale that your source content is written in. This is also the fallback locale for your project (if using `gt-next` or `gt-react`). - `locales`: An array of locales for your project. These are the locales that you want to translate your project into. See the [supported locales](/docs/platform/locale-strings#supported-locales) for more information. If you are using `gt-next` or `gt-react`, these are also the locales that your app supports. - `files`: This is an object that contains information about the content you want to translate. - `stageTranslations`: An optional boolean flag that indicates whether your project is configured to use human review. - `src`: An optional array of relative directory paths that contain translatable content. - `dictionary`: An optional string that specifies the relative path to the dictionary file. To help validate your `gt.config.json` file, you can use the [JSON Schema](https://assets.gtx.dev/config-schema.json) for the CLI. Add it to the top of your `gt.config.json` file: ```json title="gt.config.json" copy { "$schema": "https://assets.gtx.dev/config-schema.json", } ``` Here is an skeleton of the `gt.config.json` file: ```json title="gt.config.json" { "$schema": "https://assets.gtx.dev/config-schema.json", "defaultLocale": "en", "locales": ["fr", "es"], "files": { "gt": { "output": "..." }, "json": { "include": [...] }, "mdx": { "include": [...] }, "md": { "include": [...] } }, "src": ["./src", "./app", "./pages", "./components"], "dictionary": "./dictionary.json" } ``` --- ## `files` ### Supported File Types `files` should contain a key for each file type that you want to translate. You can configure your project to mix and match different file types, and have them all be translated. We currently support the following file types: - `gt`: General Translation files. - `json`: JSON files. - `mdx`: Markdown component (MDX) files. - `md`: Markdown (MD) files. - `js`: JavaScript files. - `ts`: TypeScript files. Each file type should correspond to an object that contains one or more of the following keys: - `include` - `exclude` - `transform` - `output` ### `include` If used, the value of the `include` key should be an array of glob patterns that match the files you want to translate. You must use the `[locale]` placeholder in your glob patterns to ensure that source files are found correctly, and translated files are saved to the correct location. The CLI tool will replace the `[locale]` placeholder with the `defaultLocale` value when searching for translatable files. The CLI tool will save translated files to the corresponding path, with the `[locale]` placeholder replaced with the target locale code. ```json { "include": ["docs/[locale]/**/*.json"] } ``` ### `exclude` If used, the value of the `exclude` key should be an array of glob patterns that match the files you want to exclude from translation. The pattern is the same as the `include` pattern. ```json { "exclude": ["docs/[locale]/exclude/**/*.json"] } ``` ### `transform` If used, the value of the `transform` key should be a string defining a remapping of the file name. It should contain a wildcard `*` that will be replaced with the original file name (anything before the first `.`). For example, if you want the extension of all of your translated files to have `.[locale].json` instead of `.json`, you can use the following configuration: ```json { "transform": "*.[locale].json" } ``` This is useful if your docs or i18n framework requires a specific file extension for translated files instead of subdirectory-based locale routing. ### `output` This key is exclusively used for General Translation files, specifically for saving translations locally. If you are using the GT CDN, this key is not needed. The value should be a string containing a `[locale]` placeholder indicating the location where the translations will be saved. For example, if you want to your Spanish translations to a file called `ui.es.json` in the `public/i18n` directory, you should use the following string: ```json { "output": "public/i18n/[locale].json" } ``` This option should only be used if you are using `gt-next` or `gt-react`, and want to save translations locally, instead of using the GT CDN. Currently, only one file for each locale can be generated. --- ### File Type: `gt` [#gt] **Supported Keys** - `output` (Required) **Example** ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["fr", "es"], "files": { "gt": { "output": "public/i18n/[locale].json" }, } } ``` This configuration will the CLI tool to save your French and Spanish translations to the `public/i18n/[locale].json` directory. By default, the CLI tool will not publish your translations to the GT CDN with this configuration. --- ### File Type: `json` [#json] **Supported Keys** - `include` (Required) - `exclude` (Optional) - `transform` (Optional) **Example** ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["fr", "es"], "files": { "json": { "include": ["json_files/[locale]/**/*.json"], "exclude": ["json_files/[locale]/exclude/**/*.json"] } } } ``` Let's say your project's default locale is `en`, and you want to translate your project into `fr` and `es`. With this configuration, the CLI will search for all JSON files under the subdirectory `json_files/en/` and save the translated files to `json_files/fr/` and `json_files/es/`. It will ignore any files in the subdirectory `json_files/en/exclude/`. --- ### File Type: `mdx` [#mdx] **Supported Keys** - `include` (Required) - `exclude` (Optional) - `transform` (Optional) **Example** ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["ja"], "files": { "mdx": { "include": ["content/docs/[locale]/**/*.mdx"], "transform": "*.[locale].mdx" } } } ``` This configuration will tell the CLI tool to search for all MDX files under the `content/docs/en` directory and save the translated files to the `content/docs/ja` directory. The `transform` key causes the extension of the translated files to be changed to `.ja.mdx`. --- ### File Type: `md` [#md] **Supported Keys** - `include` (Required) - `exclude` (Optional) - `transform` (Optional) **Example** ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["ja"], "files": { "md": { "include": ["content/docs/[locale]/**/*.md"], "exclude": ["content/docs/[locale]/exclude/**/*.md"], "transform": "*.[locale].md" } } } ``` This configuration will tell the CLI tool to search for all MD files under the `content/docs/en` directory and save the translated files to the `content/docs/ja` directory. The `transform` key causes the extension of the translated files to be changed to `.ja.md`. All files in the `content/docs/en/exclude` directory will be ignored. --- ### File Type: `js` [#js] **Supported Keys** - `include` (Required) - `exclude` (Optional) - `transform` (Optional) **Example** ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["fr", "es"], "files": { "js": { "include": ["scripts/[locale]/**/*.js"] } } } ``` This configuration will tell the CLI tool to search for all JavaScript files under the `scripts/en` directory and save the translated files to the `scripts/fr` and `scripts/es` directories. The `transform` key causes the extension of the translated files to be changed to `.fr.js` and `.es.js` respectively (from `.js`). --- ### File Type: `ts` [#ts] **Supported Keys** - `include` (Required) - `exclude` (Optional) - `transform` (Optional) **Example** ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["fr", "es"], "files": { "ts": { "include": ["scripts/[locale]/**/*.ts"] } } } ``` This configuration will tell the CLI tool to search for all TypeScript files under the `scripts/en` directory and save the translated files to the `scripts/fr` and `scripts/es` directories. The `transform` key causes the extension of the translated files to be changed to `.fr.ts` and `.es.ts` respectively (from `.ts`). --- ## Example Configuration Let's break down an example `gt.config.json` file: ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["fr", "es"], "files": { "gt": { "output": "public/i18n/[locale].json" }, "mdx": { "include": ["content/docs/[locale]/**/*.mdx"], "transform": "*.[locale].mdx" }, "json": { "include": ["resources/[locale]/**/*.json"], "exclude": ["resources/[locale]/exclude/**/*.json"] } } } ``` In this example, we are translating the following files with a single call to [`gtx-cli translate`](/docs/cli/translate): - All MDX files in the `content/docs/en` directory. - All JSON files in the `resources/en` directory (excluding any files in the `resources/en/exclude` directory). - All in-line `` components in your React or Next.js project. - Your `dictionary.[json|js|ts]` file. GT: Translations will be saved to `public/i18n/es.json` and `public/i18n/fr.json`. These files can be loaded using [`loadTranslations()`](/docs/react/api/config/load-translations). MDX: Translations will be saved to the `content/docs/fr` and `content/docs/es` directories. The file extensions will be changed to `.fr.mdx` and `.es.mdx` respectively (from `.mdx`). JSON: Translations will be saved to the `resources/fr` and `resources/es` directories. --- ## Next Steps Learn how to use the [init command](/docs/cli/init) to generate this configuration file. # gtx-cli: General Translation CLI tool: Usage Guide URL: https://generaltranslation.com/en/docs/cli/reference/usage.mdx --- title: Usage Guide description: Usage guide for the GT command line tool --- ## Overview This guide will walk you through the process of using General Translation's CLI tool (`gtx-cli`) to translate your project. The CLI tool is compatible with any i18n library, whether you are using `gt-next`, `gt-react`, or third-party libraries like [`next-intl`](/docs/cli/formats/next-intl-quickstart) or [`react-i18next`](/docs/cli/formats/react-i18next-quickstart). The CLI tool is responsible for connecting your project to General Translation's AI translation service. There are several ways to use the CLI tool, please navigate to the relevant section for your use case. ## Installation To install the CLI tool, run the following command: ```bash npm i --save-dev gtx-cli ``` ```bash yarn add --dev gtx-cli ``` ```bash bun add --dev gtx-cli ``` ```bash pnpm add --save-dev gtx-cli ``` --- ## Use Cases ### Translating GT projects The CLI tool can be used to translate your projects which use `gt-next` or `gt-react`. This guide assumes you have already setup your codebase to use `gt-next` or `gt-react` according to the [gt-next](/docs/next/tutorials/quickstart) or [gt-react](/docs/react/tutorials/quickstart) tutorials. If you followed the quickstart guides for `gt-next` or `gt-react`, your project has only been internationalized in your development environment. When shipping your project to production, you will need to actually generate and save the translations. This step is necessary to ensure that your API keys are not exposed to the public, due to client-side vulnerabilities for frameworks like React. 1. First, you will need to configure your project's GT settings. ```bash npx gtx-cli configure ``` This command will automatically generate an API key and project ID for your project via the dashboard. However, if you would like to manually set the API key and project ID, follow steps 2 and 3 below. 2. Next, you will need to create a project in the [General Translation dashboard](https://generaltranslation.com/dashboard). After creating a project, you will need to generate a production API key. Navigate to the "API Keys" page and click the "Create API Key" button. 3. Then, add your API key and Project ID to your environment variables. ```bash title=".env" GT_API_KEY= GT_PROJECT_ID= ``` 4. Finally, run the translation command. ```bash npx gtx-cli translate ``` By default, the CLI tool will publish the translations to the General Translation CDN, so they are ready to be used in your project. If you would like to disable this behavior (for example, if you are loading translations from a different source), disable the `CDN` setting in the [dashboard project settings](https://dash.generaltranslation.com/en/settings/project). See the [API reference](/docs/cli/translate) for more information on the `translate` command. ### Translating language files (3rd party i18n libraries or standalone GT projects) The CLI tool allows you to translate language files for 3rd party i18n libraries or with a stand-alone implementation of [`gt-next`](/docs/next/concepts/stand-alone) or [`gt-react`](/docs/react/concepts/stand-alone). Most i18n libraries rely on JSON files to store translation data. The CLI tool can be used to automatically translate these JSON files into your desired languages. 1. First, you will need to configure your project's GT settings. ```bash npx gtx-cli configure ``` This command will create a `gt.config.json` file in the root of your project, containing some basic configuration settings, such as your project's default locale and supported locales. This command will automatically generate an API key and project ID for your project via the dashboard. However, if you would like to manually set the API key and project ID, follow steps 2 and 3 below. 2. Next, you will need to create a project in the [General Translation dashboard](https://generaltranslation.com/dashboard). After creating a project, you will need to generate a production API key. Navigate to the "API Keys" page and click the "Create API Key" button. 3. Then, add your API key and Project ID to your environment variables. ```bash title=".env" GT_API_KEY= GT_PROJECT_ID= ``` 4. Finally, run the translation command. ```bash npx gtx-cli translate ``` By default, the CLI tool will look for files to translate according to the `files` property in your `gt.config.json` file. It will use the `defaultLocale` specified in your `gt.config.json` file as the source language. Translated files will be saved to the corresponding output location specified in your `gt.config.json` file. See the [configuration](/docs/cli/reference/config) docs for more information on the `files` property. If your files are not being translated, it is likely that your `gt.config.json` file is not configured correctly. The `translationsDir` should be set to the directory containing your language files, and contain a wildcard (`*`) to match all language files. For example, if your language files are stored in the `src/locales` directory, your `gt.config.json` file should look like this: ```json { "defaultLocale": "en", "supportedLocales": ["en", "fr", "es"], "translationsDir": "src/locales/*.json" } ``` ### Generating language files for GT projects The CLI tool can be used to generate language files for projects which use `gt-next` or `gt-react`. This use case is useful if you would like to use your own translation provider. Unlike other i18n libraries, `gt-next` and `gt-react` support in-line translations, meaning there is no traditional JSON file structure containing keys and values for each language. This means that in order to track changes to text, GT libraries store the hashes of the original text in the source code. This internal data structure (containing hashes) is hard to work with, and therefore the CLI tool provides a handy command to generate language files for your project. 1. First, you will need to configure your project's GT settings. ```bash npx gtx-cli configure ``` When asked if you want to save translations on the GT CDN, select the "No" option. 2. Run: ```bash npx gtx-cli generate ``` This command will generate a source file for your default locale, and all other locales you have configured for your project. The content for each file is the same, and will be merged with any previous translations you have in your project. See the [API reference](/docs/cli/generate) for more information on the `generate` command. --- ## Notes * [`gtx-cli translate`](/docs/cli/translate) is used to automatically generate translations for your project. * If you are using a 3rd party i18n library, you can automatically update all of your translation JSON files every time your project changes. Just add the [`gtx-cli translate`](/docs/cli/translate) command to your build or CD process before the build command to automatically add translations to your project. ## Next steps * See the [CLI API reference](/docs/cli) for more information. * If you want to see live translations in development (think hot reload), check out the [`` component](/docs/react/guides/jsx). # gtx-cli: General Translation CLI tool: Wrapping Behavior URL: https://generaltranslation.com/en/docs/cli/reference/wrapping.mdx --- title: Wrapping Behavior description: Specific behavior of how the CLI tool wraps the `` component --- ## Overview This page describes the exact behavior of how the CLI tool wraps the `` component. As a rule of thumb, the CLI will wrap the [``](/docs/next/api/components/t) component around any static, meaningful content. It will also wrap a [``](/docs/next/api/components/var) component around any dynamic subcontent contained within a `` component. For example, the following will be wrapped in a `` component: ```jsx
Hello, World!
->
Hello, World!
``` but the following will not: ```jsx
->
``` The CLI tool will always ensure that the final output is valid JSX and correctly uses the `` component. In some cases, such as with [logical operators](#logical-operators), some human intervention could be useful to ensure better translations with more context. Since the `` component is typically pre-translated and cached, it is important to ensure that the content is not changed at runtime. If dynamic content were allowed, every user could potentially see a different translation of the same content. If you would like to translate content that changes at runtime, you should use the [``](/docs/next/api/components/t) component instead. Static content is content that cannot change at runtime. For example, the following is static: ```jsx
Hello, World!
``` but the following is dynamic: ```jsx
{name}
```
Meaningful content is content that could feasibly be translated and has a different meaning in a different language. For example, this is meaningful: ```jsx
Hello, World!
->
Hello, World!
``` while these are not: ```jsx
``` Regardless of what language the content is viewed in, the results are always the same. Symbols such as '!', '?', '.', and "@" are considered not-meaningful, since they typically have the same meaning across languages and translate to the same symbol. The regex used to determine if content is meaningful is: ```/[\p{L}\p{N}]/u;```
Please report any bugs or unexpected behavior to us on [Github](https://github.com/generaltranslation/gt/issues). ### JSX expressions The CLI will automatically wrap expressions `{...}` in [``](/docs/next/api/components/var) components. This is because expressions are typically dynamic. ```jsx
Hello, {name}
->
Hello, {name}
``` Content contained within a `` component will not be translated. If you would like to translate dynamic content, you should use the [``](/docs/next/api/components/t) component instead. ### Static content in JSX expressions The exception to the expression-wrapping rule is when the expression contains static content. For example, the following will not be wrapped in a `` component: ```jsx

{"Hello," + " World!"}

->

{"Hello," + " World!"}

``` ### Template literals in JSX expressions The CLI will wrap template literals containing quasis (`${}`) in a [``](/docs/next/api/components/var) component, since they can be dynamic. ```jsx

{`${temp}`}

->

{`${temp}`}

``` ### Logical operators JSX expressions containing logical operators such as `&&`, `||`, and `?` will be wrapped in a [``](/docs/next/api/components/var) component, if a `` component is necessary at the top level. (i.e. if there is other meaningful content outside of the expression) ```jsx
Hello, {name && {name}} World!
```
```jsx
Hello, {name && {name}} World!
```
Within the expression, the CLI will treat elements as if they are completely independent of the rest of the expression. This means that they will be wrapped in their own `` components (to ensure all content is translatable) ```jsx
{name ? <>Hello, : <>Goodbye, }
```
```jsx
{name ? <>Hello, : <>Goodbye, } World!
```
In cases such as these, you should be using a [``](/docs/next/api/components/branch) or [``](/docs/next/api/components/plural) component instead. The CLI tool currently does not automatically use these components in a `` component, so you will need to change the code manually. The previous example should be rewritten as: ```jsx
Hello, } false={<>Goodbye, } /> World!
```
# gt-next: General Translation Next.js SDK: Production vs Development URL: https://generaltranslation.com/en/docs/next/concepts/environments.mdx --- title: Production vs Development description: Differences between production and development environments --- ## Overview `gt-next` behaves differently depending on the environment your Next.js application is running in. It detects the environment by checking the `NODE_ENV` environment variable. ## Production Behavior ### Environment Variables In production, `gt-next` will only read the `GT_PROJECT_ID` and `GT_API_KEY` environment variables. The API Key must be a Production API Key, beginning with `gtx-api-`. If you are using a Development API Key, `gt-next` will throw an error. ### Translation Loading Behavior In production, `gt-next` will attempt to load translations from the General Translation CDN, by default. If you have configured custom translation loading behavior, such as local translations, via the `loadTranslations` function, `gt-next` will use that instead. Translation hot reloading is disabled since it is in production. On-demand translation for dynamic content using the `` component or `tx()` function is enabled, but only in server components. ## Development Behavior ### Environment Variables `gt-next` will accept the `GT_PROJECT_ID` and `GT_API_KEY` environment variables. The API key can either be a Production API Key, beginning with `gtx-api-`, or a Development API Key, beginning with `gtx-dev-`. If a production API key is provided in development, `gt-next` will behave as if you are in production. This means that translation hot reloading will be disabled, and components without translations will render the original content. ### Translation Loading Behavior In development, `gt-next` will first attempt to load translations in the same way as production. These translations are loaded into memory. When rendering a component (that uses `useGT()`, ``, or `useDict()`) in a language different than the default, `gt-next` will do the following: 1. If it detects a valid, stored translation for the given content, it will render the translation. 2. If no translation is found, it will attempt to dynamically translate the content via the General Translation API. 3. After translating, the translation will be rendered, and stored in memory for future use. 4. If the translation times out, it will fallback and render the original content. Our API also internally caches development translations for a short period of time, so if the same translation is requested again, it will be served from cache. These translations are isolated at the project level, so they will not be mixed up with translations from other projects. Additionally, the cache is unique to development sessions, so cached translations will not be used in production. `gt-next` will detect changes to components that use `useGT()`, ``, or `useDict()` and will dynamically translate the modified content via our API. ## Production vs Development API Keys [#api-keys] To help distinguish between the production and development behavior of `gt-next`, we have the concept of "Production API Keys" and "Development API Keys". ### Production API Keys Production API keys are API keys beginning with `gtx-api-`. When a Production API key is provided, `gt-next` will behave as described in the [Production Behavior](#production-behavior) section. This means that if you are running your Next.js application in development mode, and you provide a Production API key, `gt-next` will behave as if you are in production. Translation hot reloading will be disabled, and components without translations will render the original content. Other than this behavior, `gt-next` will not utilize the Production API key in any way. The CLI tool reads the `GT_API_KEY` environment variable and only accepts Production API keys. The CLI tool will apply billing and rate-limiting using the "production" category. ### Development API Keys Development API keys are API keys beginning with `gtx-dev-`. When a Development API key is provided, `gt-next` will behave as described in the [Development Behavior](#development-behavior) section. When using a Development API key, billing and rate-limiting will be applied using the "development" category. Translations created with a Development API key will not be stored, and will not be available for use in production. The purpose of development translations is to allow you to test your application before shipping to production. # gt-next: General Translation Next.js SDK: Standalone i18n URL: https://generaltranslation.com/en/docs/next/concepts/stand-alone.mdx --- title: Standalone i18n description: How to use gt-next as a standalone i18n library --- ## Overview `gt-next` has feature parity with many other i18n libraries. This means that you can use `gt-next` as a standalone i18n library, without using the General Translation platform. To do this, simply don't provide any environment variables such as `GT_API_KEY` or `GT_PROJECT_ID`. See our [migration guide](/docs/next/guides/migration) for more information on how to migrate from another i18n library to `gt-next`. ## Tradeoffs Using `gt-next` as a standalone i18n library has some tradeoffs. ### Manual translation You will need to manually translate your app. If you use our platform, we automatically translate your app for you. If your project only uses [dictionaries](/docs/next/guides/dictionaries) with the `useDict()` and `getDict()` functions, you'll need to manually translate your dictionaries, as you would with any other i18n library. Make sure you load your translated dictionaries with the [`loadDictionary()`](/docs/next/api/config/load-dictionary) function. --- If your project is using inline translations with the [``](/docs/next/guides/jsx) component or the [`useGT() & getGT()`](/docs/next/guides/strings) functions, you'll also need to manually translate your strings. Since there are no keys with in-line translations, the CLI tool has a command: [`gtx-cli generate`](/docs/cli/generate) which will automatically generate template files for your project. You'll just need to edit the template files with your translations for each language. Make sure you load your translated strings with the [`loadTranslations()`](/docs/next/api/config/load-translations) function. ### No development translations Without an API key, translation hot-reload will not work. Untranslated content will only be rendered in your default language. # gt-next: General Translation Next.js SDK: T Component URL: https://generaltranslation.com/en/docs/next/concepts/t-component.mdx --- title: T Component description: Behavior of the T component --- ## Overview This is a technical page describing the behavior of the `` component in regards to performance, caching, and other technical details. ## Technical Details At its core, the `` component is a React component that renders JSX. # gt-next: General Translation Next.js SDK: Using Branches URL: https://generaltranslation.com/en/docs/next/guides/branches.mdx --- title: Using Branches description: How to use branch components --- ## Overview Branching components in `gt-next` enable dynamic content rendering based on specific conditions. These components include: - [``](/docs/next/api/components/branch): Renders content based on a matching `branch` prop. - [``](/docs/next/api/components/plural): Renders content based on pluralization rules for a given number. Both components provide powerful tools for managing conditional logic and dynamic content in localized applications. In this guide, we will cover: What are branch components? How to use branch components When to use branch components Examples Common pitfalls --- ## What are branch components? Branch components dynamically choose which content to render based on a specific condition or value. ### `` The `` component allows you to render different content based on a provided `branch` value. If no matching branch is found, the fallback `children` content is rendered. For example, the `` component is perfect for conditional rendering based on application state, user preferences, or any dynamic data. The most common use case is to use it to replace a ternary or conditional operator. ### `` The `` component extends the functionality of `` by handling pluralization and number agreement automatically. It uses the provided `n` value to determine which plural form to display, based on locale-specific rules. For example, the `` component is ideal for rendering singular and plural text dynamically, such as "1 item" vs. "2 items." Plural components are often combined with `` components to localize a number and its corresponding text. ### Use with `` The `` and `` components should be used within a [``](/docs/next/guides/jsx) component to sanitize dynamic content for translation. When used within a `` component, the content is automatically translated and rendered in your user's selected language. When used standalone, they will just render the content as-is, without translating it. --- ## How to use branch components ### Branching logic with `` The `` component is used for flexible content switching based on a `branch` value. You can define multiple possible branches, and the component will render the content corresponding to the matching branch key. Additionally, you can use other variable components in combination with the `` component. ```tsx const branch: 'option1' | 'option2' = 'option1'; Option 1

} option2={

Option 2

} > Fallback content
``` The `` component should be used within a `` component. This allows for the content to be automatically translated. See the [API Reference](/docs/next/api/components/branch) for more details. ### Pluralization with `` [#plural-logic] The `` component automates pluralization logic based on the value of `n`. The component dynamically chooses the appropriate plural form for the given number and locale. ```tsx copy const count: number = 1; {1} item.} plural={<>{count} items.} // Additional options zero={<>{count} items.} one={<>{count} item.} two={<>{count} items.} few={<>{count} items.} many={<>{count} items.} other={<>{count} items.} dual={<>{count} items.} /> ``` The available plural forms depend on the locale and follow [Unicode CLDR pluralization rules](https://cldr.unicode.org/index/cldr-spec/plural-rules). See the [API Reference](/docs/next/api/components/plural) for more details. --- ## When to use branch components Branch components are important for managing dynamic content in your application. When you need to display different content based on a condition, use ``. These conditions can be based on a variable component, a boolean, or a function. For example, if your code has a ternary operator or conditional rendering, you can use `` to replace it. ```tsx const isActive = true; // Ternary operator The user is active.

} false={

The user is inactive.

}>

Status unknown.

// Conditional rendering The user is active.

}> <>
```
```tsx // Ternary operator const isActive = true; {isActive ?

The user is active.

:

The user is inactive.

} // Conditional rendering {isActive &&

The user is active.

} ```
If you want to render content with correct pluralization, use ``. ```tsx const count = 1; 1 item

} other={

{count} items

} /> ```
```tsx const count = 1; {count === 1 ?

1 item

:

{count} items

} ```
The `` and `` components can be used standalone, without a `` component. When used standalone, they will just render the content as-is, without translating it. However, they are often used within a [``](/docs/next/guides/jsx) component to sanitize dynamic content for translation. --- ## Examples ### `` ```tsx copy import { T, Branch, Var } from 'gt-next'; export default function UserStatus() { const [status, setStatus] = useState<'active' | 'inactive' | undefined>(undefined); const [name, setName] = useState('John Doe'); return ( The user {name} is active.

} inactive={

The user {name} is inactive.

} >

Status unknown.

); } ``` In the example above, the `` component dynamically switches between 3 rendered contents based on the value of `status`. When `status` is `"active"`, the component renders: ```tsx

The user {name} is active.

``` When `status` is `"inactive"`, the component renders: ```tsx

The user {name} is inactive.

``` When `status` is neither `"active"` nor `"inactive"`, the component renders the fallback content: ```tsx

Status unknown.

``` Since the `` component is wrapped in a `` component, the rendered content is automatically translated in context. In this example, it displays different descriptions based on the user's subscription plan. ```tsx copy import { Branch } from 'gt-next'; export default function SubscriptionDetails() { const [plan, setPlan] = useState<'free' | 'premium' | 'enterprise' | undefined>(undefined); return ( You are on the Free plan. Upgrade to unlock more features!

} premium={

You are enjoying the Premium plan with full access to features.

} enterprise={

You are on the Enterprise plan. Contact support for tailored solutions.

} >

No subscription plan detected.

); } ``` * The `branch` prop determines which plan message to display. * If `plan` is `"free"`, `"premium"`, or `"enterprise"`, the corresponding message is shown. * If `plan` doesn't match any of these values, the fallback content (`"No subscription plan detected."`) is displayed. ### `` The `` component dynamically handles singular and plural content based on the value of `n`. This example displays the number of unread messages in a user's inbox. ```tsx copy import { T, Plural, Num } from 'gt-next'; export default function UnreadMessages() { const [unreadCount, setUnreadCount] = useState(1); return ( You have {unreadCount} unread message.} other={<>You have {unreadCount} unread messages.} /> ); } ``` * The `n` prop specifies the number of unread messages. * If `unreadCount` is `1`, the component renders: `"You have 1 unread message."` * For any other value, it renders: `"You have X unread messages."` where `X` is the value of `unreadCount` formatted by ``. --- ## Common Pitfalls ### Missing Branch Values [#missing-branch] If a branch value is not provided or does not match any keys, the `` component will render the fallback children content. Always ensure that the possible branch keys match the values passed to the branch prop. ```tsx copy import { Branch } from 'gt-next'; export default function StatusMessage({ status }) { return ( The user is active.

} inactive={

The user is inactive.

} >

Status unknown.

); } ``` If `status` is `undefined` or a value other than `active` or `inactive`, the fallback content `“Status unknown.”` will be displayed. ### Missing Plural Forms [#plural-locale] Remember to specify all necessary plural forms in your default language. This is how `gt-next` ensures that your application always has fallback content to display. For example, if English is your default language, you should provide all plural forms for English. ```tsx copy import { Plural, Num } from 'gt-next'; You have {count} unread message.} other={<>You have {count} unread messages.} /> ``` Here, we have provided `one` and `other` plural forms for English. Alternatively, you can also provide `singular` and `plural` for English. --- ## Notes * Branch components are essential for managing dynamic and localized content in applications. * The `` component is highly flexible and can adapt to various conditions and states. * The `` component simplifies pluralization by adhering to locale-specific rules automatically. * Always include a fallback `children` prop for better error handling and user experience. ## Next Steps * Check out [``](/docs/next/api/components/branch) and [``](/docs/next/api/components/plural) in the API Reference for more details. * Learn more about pluralization rules and branching logic in [Unicode CLDR Pluralization Rules](https://cldr.unicode.org/index/cldr-spec/plural-rules). * Explore how to use [Variable Components](/docs/next/guides/variables). # gt-next: General Translation Next.js SDK: Dictionaries URL: https://generaltranslation.com/en/docs/next/guides/dictionaries.mdx --- title: Dictionaries description: How to use dictionaries --- ## Overview In this guide, we will introduce you to dictionaries. Please feel free to skip around this page as needed. We will cover the following: What is a dictionary? How to use dictionaries Loading dictionaries for other languages Using dictionaries Production considerations **Note:** We do not recommend using dictionaries if you are using `gt-next`. Instead, please check out the [``](/docs/next/api/components/t) component. This guide is intended for those who are already familiar with dictionaries and want to learn how to use them with `gt-next`, or those who are trying to migrate from another i18n library to `gt-next`. --- ## What is a dictionary? A dictionary is a nested object with string values that can be used to store translatable content. They can be stored in a `.ts`, `.js`, or `.json` file. `gt-next` allows you to use dictionaries standalone, or in conjunction with [``](/docs/next/api/components/t) components. ### Dictionary vs `` Components The dictionary pattern has a few advantages over the [``](/docs/next/api/components/t) component: 1. **Centralized Storage**: Dictionaries store all translatable content in a single file. 2. **Historical Precedent**: The dictionary pattern is a common design pattern in the industry and is used by many other i18n libraries. At the same time, it has several major disadvantages: 1. **Complexity**: Dictionaries are more complex to set up and use than the `` component. 2. **Readability**: Dictionaries are less readable than the `` component because the content is not inline. 3. **Maintainability**: Dictionaries are more difficult to maintain than the `` component because the content is not inline, and is instead stored separately. This makes maintaining and updating translations much more difficult. 4. **Debuggability**: For the same reason, dictionaries are more difficult to debug than the `` component. When trying to debug a React component, you will have to track down where the content in the dictionary is being used, rather than just directly searching your codebase. Both design patterns are supported by our library and are not mutually exclusive. You can use a dictionary alongside `` components. ### Our advice We recommend using the [``](/docs/next/api/components/t) component because of its simplicity especially if you are new to internationalization (i18n). We offer dictionary support for those who prefer this design pattern from past experiences or for ease of integration with existing code bases. --- ## How to use dictionaries In this section, we will show you how to set up a bare-bones dictionary implementation in your Next.js application. We will walk through the following steps: Create a dictionary Reference the dictionary ### Step 1: Create a dictionary The first step is to create a dictionary. This is a `dictionary.[js|ts|json]` file that contains all the content you want to translate. Add the following content to your `dictionary` file: ```ts title="src/dictionary.ts" copy const dictionary = { greetings: { hello: 'Hello, World!' }, } export default dictionary; ``` You can also use a `dictionary.json` file to store your dictionary. This is useful if you are migrating from a different library or if you prefer to use JSON files. Here is an example of a `dictionary.json` file: ```json title="src/dictionary.json" copy { "greetings": { "hello": "Hello, World!" } } ``` The [`withGTConfig()`](/docs/next/api/config/withGTConfig) function will automatically pick up the dictionary file in your project root or `src` directory. ### Step 2: Reference the dictionary You can access dictionary entries with the [`useDict()`](/docs/next/api/dictionary/useDict) hook or the [`getDict()`](/docs/next/api/dictionary/getDict) function. Just use the function returned by the hook to access the dictionary entries by key. ```tsx title="src/components/MyComponent.tsx" copy import { useDict } from 'gt-next'; export default function MyComponent() { const d = useDict(); return (
{d('greetings.hello')}
); } ``` ```tsx title="src/components/MyComponent.tsx" copy import { getDict } from 'gt-next'; export default async function MyComponent() { const d = await getDict(); return (
{d('greetings.hello')}
); } ``` --- ## Loading dictionaries for other languages [#other-languages] By default, developers only provide a dictionary for the default language. General Translation automatically generates dictionaries for other languages and loads them with the [`loadTranslations`](/docs/next/api/config/load-translations) function. However, if you are migrating from another i18n library or already have dictionaries for other languages, you can pass them to the [`loadDictionary`](/docs/next/api/config/load-dictionary) function. `gt-next` will automatically load the corresponding dictionary for the requested locale when using the `useDict()` hook or `getDict()` function. See the [API Reference](/docs/next/api/config/load-dictionary) for more information. --- ## Using dictionaries [#usage] ### Variables You can add variables to your dictionary by using the `{variable}` syntax: ```ts title="src/dictionary.ts" copy const dictionary = { greetings: { hello: 'Hello, {name}!', // -> Hello, Alice! goodbye: 'Goodbye, {name}!' // -> Goodbye, Bob! }, } export default dictionary; ``` ```tsx title="src/components/MyComponent.tsx" copy import { useDict } from 'gt-next'; export default async function MyComponent() { const d = useDict(); return (
{d('greetings.hello', { variables: { name: 'Alice' }})} {d('greetings.goodbye', { variables: { name: 'Bob' }})}
); } ``` Read more about adding variables to your dictionary in the [`DictionaryTranslationOptions` type](/docs/next/api/types/DictionaryTranslationOptions). ### Prefixes Additionally, with [`useDict()`](/docs/next/api/dictionary/useDict), you can pass in a prefix to the function to specify a shared path in the dictionary. This is useful if you have a shared path in your dictionary that you want to use in multiple components. ```jsx title="src/dictionary.js" copy const dictionary = { greetings: { common: { hello: 'Hello, World!', goodbye: 'Goodbye, World!' }, }, } export default dictionary; ``` ```jsx title="src/components/MyComponent.js" copy import { useDict } from 'gt-next'; export default async function MyComponent() { // All translation paths such as 'hello' will be prefixed with 'greetings.common.' const d = useDict('greetings.common'); // [!code highlight] return (
{d('hello')} {/* hello -> greetings.common.hello */} {d('goodbye')} {/* goodbye -> greetings.common.goodbye */}
); } ``` --- ## Production considerations ### Deploying to production Make sure to run the translate command before deploying to production, so that all translations are available at runtime. We recommend adding it to your in your CD pipeline or as a part of your build script. ```json title="package.json" copy { "scripts": { "build": "npx gtx-cli translate && ", } } ``` For a more detailed guide on deploying your application, please refer to the [Deployment](/docs/next/tutorials/quickdeploy) guide. For more information on the command, please refer to the [CLI Tool](/docs/cli/translate) reference guide. ### Behavior: Development vs Production In development, the function returned by the `useDict()` hook will translate dictionary entries on-demand. This means that when the component is rendered, it will perform a translation immediately. We do this for convenience to make development with other languages easier. To enable this behavior, just add a [Dev API key](/docs/next/concepts/environments) to your environment. In production, the `d()` function will translate content at build time. This means that you have to run the translation command before deploying your application. **Tip:** If you want to simulate production behavior in development, just use a production API key in your development build. --- ## Notes * Dictionaries are an alternative to the `` component. They can be used in conjunction with `` components or standalone. * Dictionary translations occur at build time, so you have to add the [`translate`](/docs/cli/translate) command to your build process. * Dictionaries can be used with prefixes to specify a subset of the dictionary. ## Next steps * Learn about the [`` component](/docs/next/api/components/t) and how to use it in your Next.js application. * Learn how to ship to production with our [deployment guide](/docs/next/tutorials/quickdeploy). # gt-next: General Translation Next.js SDK: Translating Dynamic Content URL: https://generaltranslation.com/en/docs/next/guides/dynamic-content.mdx --- title: Translating Dynamic Content description: How to translate dynamic content in Next.js server components --- ## Overview This guide will walk you through how to use the [`` component](/docs/next/api/components/tx) and the [`tx()`](/docs/next/api/strings/tx) function to translate dynamic content in Next.js server components. By the end of this guide, you will learn the proper syntax for using these components and functions. We will cover the following: What is dynamic content? When should you translate dynamic content? How to use the `` component How to use the `tx()` function Examples Production considerations Common pitfalls ## What is dynamic content? Dynamic content is content that is not known at build time. These could include things like variables, user names, input fields, etc. For example, the following is dynamic content: ```jsx const username = 'John Doe';

Your username is {username}

``` ## When should you translate dynamic content? In most cases, you can use [Variable Components](/docs/next/guides/variables) or [Branching Components](/docs/next/guides/branches) to handle dynamic content. These components are designed to handle dynamic content with the `` component, and thus we recommend using them whenever possible. However, there are some cases where you need to translate dynamic content on-demand. For example, if you have a chat message that is created by a user, and want to display it in a different language, you can use `gt-next` to translate it on-demand. ## How to use the `` component The `` component is only available in Next.js server components. This is because it hits the General Translation API using an API key, which is only available on the server for security reasons. ```jsx copy import { Tx } from 'gt-next'; const message = 'Hello, world!'; {message} ``` Simply wrap whatever JSX content you want to translate with the `` component. The `` component will then translate the content on-demand, and render the translated content asynchronously. See the [API reference](/docs/next/api/components/tx) for more information. ## How to use the `tx()` function The `tx()` function is only available in Next.js server components. This is because it hits the General Translation API using an API key, which is only available on the server for security reasons. The `tx()` function is a server-side function that can be used to translate strings dynamically. ```jsx copy import { tx } from 'gt-next/server'; const message = 'Hello, world!'; const translatedMessage = await tx(message); ``` The `tx()` function returns a promise that resolves to the translated string. See the [API reference](/docs/next/api/strings/tx) for more information. ## Examples ### Rendering dynamic content ```jsx copy import { Tx } from 'gt-next'; export default function ChatMessage({ message }: { message: ReactNode }) { return ( {message} ); } ``` ### Translating a string ```jsx copy import { tx } from 'gt-next/server'; export default async function ChatMessage({ message }: { message: string }) { const translatedMessage = await tx(message); return (
{translatedMessage}
); } ``` ## Production considerations The behavior of the `` component and the `tx()` function is the same in development as it is in production. Regardless of the type of API key you use, the behavior is the same. In both cases, translations are completed live, on-demand. ## Common pitfalls ### Unnecessary use of `` and `tx()` If you are using the `` component or the `tx()` function, you should only do so if you are truly unable to use [Variable Components](/docs/next/guides/variables) or [Branching Components](/docs/next/guides/branches) with the `` component. Using `` and `tx()` when you don't need to is a waste of resources, and will quickly use up your API quota. Additionally, your content will be rendered slower, as the translations are completed on-demand. # gt-next: General Translation Next.js SDK: Translating JSX URL: https://generaltranslation.com/en/docs/next/guides/jsx.mdx --- title: Translating JSX description: How to internationalize JSX components --- ## Overview This guide will walk you through how to use the [`` component](/docs/next/api/components/t) to internationalize JSX content. By the end of this guide, you will know the correct syntax for using the `` component and what to avoid. We will cover the following: How to use the `` component Additional options When to use the `` component Examples Production considerations Common pitfalls If you are looking for how to use [Variable Components](/docs/next/guides/variables) or [Branching Components](/docs/next/guides/branches), please refer to their respective guides. --- ## How to use the `` component Let's say you have some HTML content that you want to translate. ```jsx function Greeting() { return

Hello, world!

; } ``` All you have to do is wrap the content in a `` component. ```jsx import { T } from 'gt-next'; function Greeting() { return

Hello, world!

; } ``` Depending on the current language your user has selected, this will render the appropriate translation. See [switching languages](/docs/next/guides/languages) for more information on how to allow your users to switch languages. --- ## Additional Options ### Context In some cases, you may want to provide additional context to the translation. This can be done by passing a `context` prop to the `` component. ```jsx Click on the toast to dismiss it. ``` This is useful in cases where words may have multiple meanings depending on the context. For example, "toast" can refer to the food or a pop-up notification. The context prop is helpful for the AI to understand the intent of the translation. ### `id` You can also pass an `id` prop to the `` component. This is useful for debugging purposes and makes editing the translation easier. ```jsx Click on the toast to dismiss it. ``` --- ## When to use the `` component While the `` component is very flexible, it is not always the best solution. You should always try to use the `` component when you have any **static HTML or JSX content.** ### When not to use the `` component **DO NOT** use the `` component when you have any unsafe **dynamic** content. Here, dynamic content means any content that could change at runtime. This rule does not apply if you are using [Variable Components](/docs/next/guides/variables) or [Branching Components](/docs/next/guides/branches). **Note:** Variable components are a special case where the content is dynamic, but the content has been wrapped and sanitized, so it is safe to use the `` component. Content wrapped in variable components are never translated directly by the `` component. The following examples show invalid usage of the `` component: ```jsx

Your username is {username}

``` ```jsx

Current date: {new Date().toLocaleDateString()}

``` ```jsx

Logical Expressions: {username === 'admin' ? 'Yes' : 'No'}

``` ```jsx

Conditional Rendering: {isAdmin ? 'Yes' : 'No'}

``` In the above examples, the content can be safely internationalized using [variable components](/docs/next/guides/variables) and [branching components](/docs/next/guides/branches). ```jsx const chatMessage = getChatMessageFromServer();

{chatMessage}

``` In this example, the content is fully dynamic, so it should be translated on the server side before being passed to the client. See the [core](/docs/core) library for more information on how to dynamically translate content via our API. --- ## Examples Here are some examples of how to use the `` component. These are all correct. 1. HTML content ```jsx

Hello, world!

```
```jsx

Hello, world!

```
2. Simple JSX content ```jsx ``` ```jsx ``` 3. Complex JSX content ```jsx
Free Usage

You are nearing your free monthly limit. Please upgrade your plan to avoid any disruptions to your service.

```
```jsx
Free Usage

You are nearing your free monthly limit. Please upgrade your plan to avoid any disruptions to your service.

```
The `` component can handle any nested content in the same component. --- ## Production Considerations [#production] ### Deploying to production Make sure to run the translate command before deploying to production, so that all translations are available at runtime. We recommend adding it to your CD pipeline or as a part of your build script. ```json title="package.json" copy { "scripts": { "build": "npx gtx-cli translate && ", } } ``` For a more detailed guide on deploying your application, please refer to the [Deployment](/docs/next/tutorials/quickdeploy) tutorial. For more information on the command, please refer to the [CLI Tool](/docs/cli/translate) reference guide. ### Behavior: Development vs Production In development, the `` component will translate content on-demand. This means that when the component is rendered, it will perform a translation immediately. The library does this for convenience to make development with other languages easier. To enable this behavior, just add a Dev API key to your environment. In production, all translations that the `` component uses are completed at build time. This means that you have to run the translation command before deploying your application. **Tip:** If you want to simulate production behavior in development, just use a production API key in your development build. ### Privacy Concerns With some exceptions, all content wrapped in a `` component is sent to the General Translation API for translation. This might not be desirable for rendering sensitive data, such as usernames, account numbers, etc. To circumvent this issue, use [Variable Components](/docs/next/guides/variables#privacy) to handle private information. This ensures that no sensitive data is sent to the General Translation API for translation. Localization of any content wrapped in a variable component is handled locally. --- ## Common Pitfalls ### Direct descendants only [#direct-text] The `` component only translates text passed directly as a child. This means that if you have content inside a component that is not directly passed to ``, it will not be translated. Let's illustrate this with an example: ```jsx copy function UntranslatedContent() { return (

This content is not translated

); } export default function DisplayGreetings() { return (

Hello, this text will be translated

); } ``` In this example, the content inside `` will not be translated. Only the content directly inside `` will be translated, like the `

` tag and its children. This occurs because of how React renders components. It is a bit complicated, but the gist is that React does not know the content of a component until it has rendered. Therefore, the contents of components like `` are not translated. However, any text directly between the two `` tags will be translated. **Note:** A good rule of thumb is that any content that is *literally* between the two `` tags in the file will be translated. You can always add another `` to translate the content that is not being translated, though nesting `` components is not recommended. #### What's the fix? Wrap the text in the `` component directly, like so: ```jsx copy function TranslatedContent() { return (

This content IS translated

); } export default function DisplayGreetings() { return ( <>

Hello, this text will be translated

); } ``` ### Nested `` Components [#nested-t] Nesting `` components is not allowed. Because of React's rendering system, this can lead to unexpected behavior and performance issues. Here is an example of **what not to do**: ```jsx copy function SomeComponent() { return ( Hello, friend! ); } export default function NestedTranslation() { return ( {/* Don't do this! */} Hello, world! {/* This still counts. Don't do this! */} ); } ``` The solution here is to remove the outtermost `` component. ### Translating dynamic content If you attempt to wrap dynamic content with the `` component, the CLI tool will error. For example, the following will error: ```jsx const username = 'John Doe';

Your username is {username}

``` To get around this, try to use [Variable Components](/docs/next/guides/variables) or [Branching Components](/docs/next/guides/branches) to wrap the dynamic content. Alternatively, if your content truly is dynamic and needs to be translated on-demand, you can use the [`` component](/docs/next/guides/dynamic-content). --- ## Summary * `` components are used to internationalize arbitrary JSX Content. * `` components should not be used for dynamic content, without using variable components or branching components. * In development, the `` component will translate content on-demand. * In production, all translations that the `` component uses are completed at build time. ## Next Steps * Read about the [API](/docs/next/api/components/t) for the `` component. * Explore [Variable Components](/docs/next/guides/variables) and [Branching Components](/docs/next/guides/branches). * Learn about [translating strings](/docs/next/guides/strings). # gt-next: General Translation Next.js SDK: Changing Languages URL: https://generaltranslation.com/en/docs/next/guides/languages.mdx --- title: Changing Languages description: How to change the language of your Next.js app --- ## Overview In this guide, we'll show you how to change the language of your Next.js app. If you have not yet setup your app with `gt-next`, please refer to the [quickstart guide](/docs/next) before continuing. There are three ways to change the language of your app using `gt-next`. 1. Using the [`useSetLocale()`](/docs/next/api/helpers/useSetLocale) hook 2. Using the [``](/docs/next/api/components/localeSelector) component 3. Using the [`useLocaleSelector()`](/docs/next/api/helpers/useLocaleSelector) hook 4. Using [middleware i18n routing](/docs/next/guides/middleware) We'll cover the first three methods in this guide. See the [middleware routing](/docs/next/guides/middleware) guide for more information on how to change the language of your app using middleware. ## Using the `useSetLocale` hook The `useSetLocale` hook is a client-side hook that allows you to change the language of your app. It must be used within a `GTProvider` component. ```tsx import { useSetLocale } from 'gt-next/client'; export default function MyComponent() { const setLocale = useSetLocale(); return ; } ``` Simply provide the locale you want to change to as the argument to the callback function returned by the `useSetLocale` hook. ## Using the `` component The `` component is a client-side component that allows you to change the language of your app. It must be used within a `GTProvider` component. This is a bare-bones UI dropdown that displays all the locales you have enabled in your project, and allows users to select a different locale. ```tsx import { LocaleSelector } from 'gt-next/client'; export default function MyComponent() { return ; } ``` ## Using the `useLocaleSelector` hook Alternatively, if you would like to create your own locale selector component, you can use the `useLocaleSelector` hook. This hook returns the current locale, the list of locales your project supports, and the `useSetLocale` hook. Here is an example of how to use the `useLocaleSelector` hook to create a custom locale selector component. ```tsx copy import { useLocaleSelector } from 'gt-next/client'; import { getLocaleProperties } from 'generaltranslation'; function capitalizeLanguageName(language: string): string { if (!language) return ''; return ( language.charAt(0).toUpperCase() + (language.length > 1 ? language.slice(1) : '') ); } export default function LocaleDropdown({ className }: { className?: string }) { // Retrieve the locale, locales, and setLocale function const { locale, locales, setLocale } = useLocaleSelector(); // Helper function to get the display name of a locale const getDisplayName = (locale: string) => { return capitalizeLanguageName( getLocaleProperties(locale).nativeNameWithRegionCode ); }; // If no locales are returned, just render nothing or handle gracefully if (!locales || locales.length === 0 || !setLocale) { return null; } return ( ); } ``` See the [API reference](/docs/next/api/helpers/useLocaleSelector) for more information. ## Next steps - Learn more about the [`useSetLocale`](/docs/next/api/helpers/useSetLocale) hook. - Learn more about the [``](/docs/next/api/components/localeSelector) component. - Learn more about the [`useLocaleSelector`](/docs/next/api/helpers/useLocaleSelector) hook. - Learn more about [middleware i18n routing](/docs/next/guides/middleware). # gt-next: General Translation Next.js SDK: Local Translations URL: https://generaltranslation.com/en/docs/next/guides/local-tx.mdx --- title: Local Translations description: How to set up local translations for your Next.js app --- ## What are local translations? Local translations are stored in your app's bundle, as opposed to being fetched from a CDN (Content Distribution Network). Let's say that you have added the [`gtx-cli translate`](/docs/cli/translate) command to your CD process. This will generate translations in JSON format for your app. The final step is to get these translations out of our API and into your app, where they can be used. There are two ways to do this: * **In your app's bundle:** After translations are generated, save them to your app's bundle. * **In a CDN (default):** Fetch translations from a CDN at runtime. By default, `gt-next` will fetch translations from the General Translation CDN, and when translating your app using our API, translations will be automatically saved to our CDN. ## Overview This guide will show you how to store translations in your Next.js app bundle, rather than using an external CDN, such as ours. This means that translations will live in your app's code and avoids reliance on external infrastructure. In this guide, we will walk you through: The trade-offs of using local translations. How to set up local translations for your Next.js app. --- ## Trade-offs ### What are the benefits? 1. **Faster load times:** Local translations are served directly from your app, meaning that they will load faster than translations served from a CDN. 2. **No reliance on external services:** Your app's ability to load translations is not dependent on CDN uptime. With `gt-next`, if translations are not found for a given locale, the app will automatically fall back to the default language and display the original content. ### What are the drawbacks? 1. **Increased bundle size:** Local translations will increase your app's bundle size as they will be served alongside your app. This means that your app may take longer to load on the client. 2. **Content management:** If you want to edit a translation (i.e., you do not like how your content has been phrased in a different language), you must redeploy your app with the new translation every time you make changes. --- ## Setup ### Prerequisites Make sure that you have already setup your Next.js app with GT. If not, please complete the [Quick Start Guide](/docs/next) first. ### Steps Add a `loadTranslations.[js|ts]` file under `./src` with the following content: ```ts title="src/loadTranslations.ts" copy export default async function loadTranslations(locale: string) { const t = await import(`../public/_gt/${locale}.json`); return t.default; } ``` ```js title="src/loadTranslations.js" copy export default async function loadTranslations(locale) { const t = await import(`../public/_gt/${locale}.json`); return t.default; } ``` Run the following command in your project root, and when asked if you want to save translations on the GT CDN, select the "No" option. ```bash npx gtx-cli configure ``` When asked for the path to the translations directory, enter `./public/_gt`. Alternatively, you can manually configure the `gt.config.json` file to use local translations. See the [CLI Configuration](/docs/cli/reference/config#gt) docs for more information. Now, when you run the translate command, translations will be automatically downloaded and included in your codebase. ```bash npx gtx-cli translate ``` The `loadTranslations` function will then be used to load these translations into your app. That's it! Your app will now only load translations from your local files. ### Further customization You can further customize the `loadTranslations` function to load translations from other sources, such as your database or your own CDN. See the [`loadTranslations()`](/docs/next/api/config/load-translations) docs for more information. --- ## Notes * Local translations are an alternative to fetching translations from a CDN. * There are benefits and drawbacks to using local translations, which are discussed in the [Trade-offs](#trade-offs) section. ## Next steps * See [`loadTranslations()`](/docs/next/api/config/load-translations) for more information on writing a custom translation loader. # gt-next: General Translation Next.js SDK: Middleware URL: https://generaltranslation.com/en/docs/next/guides/middleware.mdx --- title: Middleware description: A step by step guide on adding internationalization (i18n) middleware routing to your application --- ## Overview This guide will walk you through adding i18n middleware routing and localized paths to your Next.js application using `gt-next`'s built-in middleware. ### What is i18n middleware routing? Creating new routes for each language has the advantage of making your website more user friendly and improve SEO. i18n routing allows you to associate specific URLs with different locales. For example, you can have `/en/airplanes` for English, `/zh/airplanes` for Chinese, and so on. You can take this one step further with localized paths. These are an extension of i18n routing that allow you to specify an alias path for a locale. For example, you can specify `/en/airplanes` for English, `/zh/飞机` for Chinese, and so on. --- ## Set up i18n routing We will take you through two easy steps to add i18n routing to your Next.js application: Add a dynamic route to your app folder. Create the middleware file. ### Step 1: Add a Dynamic Route [#dynamic-route] Insert a directory in your app folder called `[locale]` (e.g., `app/[locale]`). Include all of your pages and layouts under this directory. Ensure all special files inside `app/` are nested under `app/[locale]`. ### Step 2: Add the middleware file [#middleware] In Next.js, create a file called `middleware.js` (or `.ts` if you are using TypeScript) inside the root directory. If you are using the `src/` folder, place it in `src/middleware.js` (or `.ts`) instead. Add the [`createNextMiddleware()`](/docs/next/api/middleware/createNextMiddleware) function to the file. ```js title="middleware.js" copy import { createNextMiddleware } from 'gt-next/middleware' export default createNextMiddleware(); export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next (internal files) * - static files */ "/((?!api|static|.*\\..*|_next).*)", ], } ``` --- ## Set up localized paths You can specify localized paths through the `pathConfig` option in the middleware file. ```js title="middleware.js" copy export default createNextMiddleware({ pathConfig: { // You can specify a shared path (optional) // This will create "/en/about" and "/zh/about" "/about": "/about", // Specify localized paths // This will create "/en/airplanes" and "/zh/飞机" "/airplanes": { "zh": "/飞机", } // Add dynamic path parameters // This will create "/en/airports/123" and "/zh/飞机机场/123" "/airports/[id]": { "zh": "/飞机机场/[id]", } }, }); ``` In this example we create a default path for `/en/about` and localized paths for `/en/airplanes` and `/en/airports/[id]`. In Chinese, these will be aliased to `/zh/about`, `/zh/飞机` and `/zh/飞机机场/[id]` respectively. **Tip:** Because the `/about` path remains the same for all locales, you don't need to include it in the `pathConfig` object. Any paths that are not specified in the `pathConfig` object will use the same path for all locales following the locale prefix. --- ## Routing behavior ### Default locale prefixing By default, your `defaultLocale` (a.k.a. your app's default language) will not be prefixed with a locale code in the url. For example, if your default locale is `en` and you have a page at `/about`, it will be accessible at `/about` in English. However, in Chinese, it will be accessible at `/zh/about` in Chinese. If you do not want this behavior, it can be disabled by setting the `prefixDefaultLocale` to `false` in the middleware configuration. ### Locale detection and redirection The middleware will detect the user's locale based on (1) the url path locale, (2) the referrer locale, (3) the accepted languages from the browser, and (4) finally the `defaultLocale`. The user will then be redirected accordingly. Locale is always first checked from the url path. This means that if you visit `/zh/about`, your language will assume to be Chinese. If the page you visit is not prefixed by a locale, then the middleware will check the user's previous locale. For example, if you are on `/zh`, and you visit `/about`, your language will assume to be Chinese, and you will be redirected to `/zh/about`. If neither of these are available, then locale detection will fallback to the user's browser language. For instance, if someone's preferred language is Chinese, and they visit `/about` for the firs time, they will be redirected to `/zh/about`. If none of these conditions are met, then the `defaultLocale` will be used as the fallback. If at any time a localized version of the page exists, they will be redirected to the localized url. For instance, `/zh/airplanes` will always redirect to `/zh/飞机`. #### Edge case: Localized paths without locale prefix If you navigate to a localized path without the locale prefix (e.g., `/飞机`), the middleware will prefix that path with whatever it thinks your current locale is. For example, visiting `/飞机` will only redirect to `/zh/飞机` if the middleware explicitly recognizes your locale as `zh`. This is great but it only works when the middleware thinks your locale is `zh`. Otherwise, your path will be prefixed with your current locale. For example, visiting `/飞机` will redirect to `/en/飞机` if the middleware thinks your locale is `en`. This will result in a 404. We recommend always using the path from your `defaultLocale` for any links in your project. This will always automatically redirect to the correct locale localized path. ```jsx About Planes Airport 123 ``` If you want to explicitly link to a different locale, then you can do so by using the localized path. ```jsx About in Chinese Planes in Chinese Airport 123 in Chinese ``` --- ## Notes * i18n routing changes the URL structure of your application. Each language has its own URL. * The middleware file is required to handle the routing logic. * You can specify the supported locales in the middleware configuration and next config file. ## Next Steps * See the API docs for [`createNextMiddleware()`](/docs/next/api/middleware/createNextMiddleware). # gt-next: General Translation Next.js SDK: Migrating URL: https://generaltranslation.com/en/docs/next/guides/migration.mdx --- title: Migrating description: Learn how to migrate a project to gt-next --- ## Overview This guide will cover the steps needed to migrate a project that's already using an i18n library to gt-next. We'll also provide some tips and suggestions for how to make the migration as smooth as possible. ## Prerequisites - A project that is currently using another i18n library. - A basic understanding of the `gt-next` library. ## Why migrate? There are many reasons why you might want to migrate your project to gt-next. Here are just a few: - **No more JSON files:** Never manage translations in JSON files again. All of your content lives in-line with your code, where it belongs. - **Automatic translations:** Generate high quality, context-aware translations with our CLI tool. You'll never have to wait for translations again. - **Experiment in dev:** Easily experiment with translations in development with translation hot-reloading. ## Setup Install `gt-next` and the `gtx-cli` CLI tool. ```bash npm i gt-next npm i --save-dev gtx-cli ``` ```bash yarn add gt-next yarn add --dev gtx-cli ``` ```bash bun add gt-next bun add --dev gtx-cli ``` ```bash pnpm add gt-next pnpm add --save-dev gtx-cli ``` Create a `gt.config.json` file in the root of your project containing a `defaultLocale` property and a `locales` array. ```json title="gt.config.json" copy { "defaultLocale": "en", "locales": ["en", "fr", "es"] } ``` Then, add the `` component to the root layout of your app. ```tsx title="app/layout.tsx" copy import { GTProvider } from 'gt-next' export default function RootLayout({ children }) { return ( {children} ) } ``` Next, add `withGTConfig` to your `next.config.js` file. ```js title="next.config.ts" copy import withGTConfig from 'gt-next/next-config' const nextConfig = { // Your next.config.ts options } export default withGTConfig(nextConfig, { // Your GT configuration }) ``` For more detailed steps, see the [quickstart guide](/docs/next). At this point, you have 3 options: 1. Fully migrate your entire project to `gt-next`, and remove the old i18n library. 2. Fully migrate your project, but keep using dictionaries from the old i18n library. 2. Keep using the old i18n library for now, and only migrate part of your project to `gt-next`. For more details on each option, see the [migration strategies](#strategies) section. ## Migration strategies [#strategies] ### Option 1: Fully migrate your entire project This option is the most straightforward, and will also require the most code changes in one go. After you've setup your project, you'll need to search for all instances of your old i18n library and replace them with `gt-next`. If your app is using React hooks such as `useTranslation`, search for all instances of `useTranslation` in your codebase and replace them with `useGT`. Then, you'll need to replace all the string keys with their actual string values. For example, if your old code looks like this: ```json title="dictionary.json" { "hello": { "description": "Hello, world!" } } ``` ```tsx export default function MyComponent() { const { t } = useTranslation() return
{t('hello.description')}
} ``` You'll need to replace it with: ```tsx export default function MyComponent() { const { t } = useGT() return
{t('Hello, world!')}
} // OR export default function MyComponent() { return Hello, world! } ``` Do this for all instances of your old i18n library. ### Option 2: Fully migrate your project, but keep using dictionaries from the old i18n library Let's say that you want to migrate your project to `gt-next`, but you want to keep using dictionaries from the old i18n library and only use GT in-line features for new content. In this case, you can do something similar to Option 1: Find all instances of your old i18n library, such as `useTranslation` hooks, and replace them with `useDict` hooks. The `useDict` hook behaves very similarly to `useTranslation` hooks, and you can use it in the same way. ```tsx import { useTranslation } from 'react-i18next' export default function MyComponent() { const { t } = useTranslation() return
{t('hello.description')}
} ```
```tsx import { useDict } from 'gt-next' export default function MyComponent() { const t = useDict() return
{t('hello.description')}
} ```
In terms of configuration, you'll need to create a `dictionary.[js|ts|json]` file in your project root or `src` directory. Copy the contents of your old dictionary file into this new file. The initialization `withGTConfig` function in `next.config.js` will automatically pick up the dictionary file in your project root or `src` directory. See the [dictionaries](/docs/next/guides/dictionaries) guide for more details. ### Option 3: Keep using the old i18n library for now, and only migrate part of your project to `gt-next` This option is the most flexible, and will require the least code changes in one go. In this case, you can do something similar to Option 2, but only migrate part of your project to `gt-next`. For example, you can keep using the old i18n library for some components, and only use `gt-next` for others and for new content. This option is not recommended, as you will have to manage two different i18n libraries in your project, which may be complex and lead to bugs. ## Migration tips ### 1. Use the `useGT` hook or `` component as much as possible Wherever possible, we recommend using the `useGT` hook or `` component. This will make editing your content much easier in the future, and make your codebase much more readable. ### 2. Use the `useDict` hook for existing content The `useDict` hook is a great way to keep using your existing dictionaries. We offer it as a way to make migration easier, but we don't recommend using it for new content. ### 3. Using AI If you are using AI to help you migrate your project, we have a `LLMs.txt` and `LLMs-full.txt` available at: - [LLMs.txt](/llms.txt) - [LLMs-full.txt](/llms-full.txt) These files contain the full content of these docs, so your AI tool will have access to all the information it needs to help you migrate your project. # gt-next: General Translation Next.js SDK: Right-to-Left Support URL: https://generaltranslation.com/en/docs/next/guides/rtl.mdx --- title: Right-to-Left Support description: A step by step guide on adding Right-to-Left (RTL) support to your application --- ## Overview While most languages are written left-to-right (LTR), some languages are written right-to-left (RTL). These languages include Arabic, Hebrew, Persian, and Urdu which have a combined total of over 500 million speakers worldwide. Look at the General Translation landing page in [English](https://generaltranslation.com/en-US/welcome) and [Arabic](https://generaltranslation.com/ar/welcome) to illustrate the difference between ltr and rtl rendering. ## Guide To add RTL support to your application, all we need to do to is determine the direction of the language and set the direction of the text on the screen accordingly. You can use the `getLocaleDirection()` function from `generaltranslation` library to determine if a language goes `"rtl"` or `"ltr"`. Use the `getLocale()` function to get the locale in the root layout, then add the `lang` and `dir` props to the `` tag: ```javascript title="my-app/app/layout.tsx" copy import { getLocale } from 'gt-next' import { getLocaleDirection } from 'generaltranslation'; export default async function RootLayout({ children }) { const locale = await getLocale(); // e.g. "ar" for Arabic const dir = getLocaleDirection(locale); // e.g. "rtl" for "right-to-left" return ( {children} ) } ``` # gt-next: General Translation Next.js SDK: Static Site Generation URL: https://generaltranslation.com/en/docs/next/guides/ssg.mdx --- title: Static Site Generation description: How to support static site generation for your i18n app --- ## Overview This guide will show you how to setup your i18n app to support static site generation. --- ### What is static site generation? [Static site generation](https://nextjs.org/docs/pages/building-your-application/rendering/static-site-generation) (SSG) is a feature of Next.js that allows you to generate static pages at build time. This is useful for performance and SEO. ## SSG for the `app` router ### Requirements There are a few requirements to enable static site generation for your i18n app. Depending on whether you are using the `app` or `pages` directory, the requirements are slightly different. 1. Your app must be using the Next.js app router. 2. Your app must support i18n routing (see [i18n routing](/docs/next/guides/middleware)) 3. Your app must be using local translations (see [local translations](/docs/next/guides/local-tx)) ### Steps **Step 1:** First, make sure your app has a `` component at the root layout. ```tsx title="app/[locale]/layout.tsx" import { GTProvider } from 'gt-next'; ``` Since the app is using i18n routing, the provider should be placed in the `[locale]/layout.tsx` file. SSG requires all parameters to be known at build time. This includes the locale for every statically generated page. Since the `` component is responsible for providing the translation context to your app, it must know the locale. For the same reason, your app must be using i18n routing (since each route must correspond to a specific locale, for a specific page). **Step 2:** Next, make sure your app is using the `loadTranslations` function to load translations. Additionally, pass in the locale as a parameter to the ``. You can obtain the locale from the `params` object. ```tsx title="app/[locale]/layout.tsx" import { loadTranslations } from '@/i18n/loadTranslations'; import { GTProvider } from 'gt-next'; export default async function RootLayout({ children, params, }: { children: React.ReactNode; params: Promise<{ locale: string }>; }) { const { locale } = await params; return ( {children} ) } ``` **Step 3:** Then, make sure all of your hooks and components are importing from `gt-next/client`. ```tsx import { useGT } from 'gt-next/client'; import { T } from 'gt-next/client'; ``` This is important because hooks and components imported from `gt-next/client` never read headers, which don't exist at build time for statically generated pages. Make sure you have configured your Next.js app to use the [`getStaticParams` function](https://nextjs.org/docs/app/api-reference/functions/generate-static-params) correctly! That's it! Your app should now support static site generation for multiple languages! If you've followed the steps above and your pages are still not being statically generated, double check that all of your hooks and components are importing from `gt-next/client`. As a rule of thumb, anything that reads headers or cookies will prevent SSG. This means you can't use any of the following: - `await getGT()` - `await getLocale()` - `await getDict()` - `import { T } from 'gt-next'` ## SSG for the `pages` router 🚧 This section is currently under construction. 🚧 # gt-next: General Translation Next.js SDK: Translating Strings URL: https://generaltranslation.com/en/docs/next/guides/strings.mdx --- title: Translating Strings description: How to internationalize strings --- ## Overview This guide will walk you through how to internationalize strings in your Next.js app using the [`useGT()`](/docs/next/api/strings/useGT) hook & [`getGT()`](/docs/next/api/strings/getGT) function. We will cover the following: When to use the `useGT()` hook How to use the `useGT()` hook Using variables Examples Common pitfalls In this guide, when we refer to the `useGT()` hook, we are also referring to the `getGT()` function. **The only difference between the two is when to use them.** The `getGT()` function is an asynchronous server-side function that returns a promised function, while the `useGT()` hook returns the function directly. Use the `getGT()` function in server components, and the `useGT()` hook in client components. ```tsx title="src/app/page.tsx" import { getGT } from 'gt-next/server'; export async function MyComponent() { const translate = await getGT(); const translatedString = translate('Hello, world!'); return
{translatedString}
; } ```
```tsx title="src/app/page.tsx" 'use client'; import { useGT } from 'gt-next/client'; export function MyComponent() { const translate = useGT(); const translatedString = translate('Hello, world!'); return
{translatedString}
; } ```
--- ## When to use the `useGT()` hook The `useGT()` hook is a React hook that can be used to translate strings. In most cases, you can use the [`` component](/docs/next/guides/jsx). However, in cases where JSX is not appropriate, the `useGT()` hook can be used. Some cases where the `useGT()` hook could be more appropriate are: - In properties that expect strictly strings, such as `placeholder` or `title` attributes. - When the string is part of a larger object, for example: ```jsx copy const user = { title: 'Mr.', name: 'John', description: 'John is a software engineer at General Translation', } ``` Here, only the `description` property should be translated. Wherever possible, you should use the [`` component](/docs/next/guides/jsx). The `` component allows you to translate JSX content, and is the recommended way to translate strings. --- ## How to use the `useGT()` hook The `useGT()` hook has to be called within the [``](/docs/next/api/components/gtprovider). To translate a string, simply pass the string directly to the function returned by the hook. ```tsx copy import { useGT } from 'gt-next/client'; export function MyComponent() { const translate = useGT(); return
{translate('Hello, world!')}
; } ``` Unlike traditional i18n libraries, the `useGT()` hook does not require you to pass a `key` to the function. Instead, the string is passed directly to the function. This means that you don't need to use dictionaries! ## How to use the `getGT()` function On the other hand, since the `getGT()` function is an asynchronous server-side function, it can be used in server components, and does not need to be called within the ``. The context for `getGT()` is handed by the `withGTConfig` function in your `next.config.ts` file. ```tsx copy import { getGT } from 'gt-next/server'; export async function MyComponent() { const translate = await getGT(); return
{translate('Hello, world!')}
; } ``` ## Using variables Often, you will need to translate strings that contain variables. For example, you may need to translate a string that contains numerical values. To add variables, simply add the variable to the string as a placeholder with `{variable}`, and pass an object as the second argument to the function returned by the hook. ```jsx copy const price = 100; const translate = useGT(); translate('There are {count} items in the cart', { variables: { count: 10 } }); ``` The `{count}` placeholder will be replaced with the value of the `count` variable. This allows you to display dynamic values in your translations. For more information on the API, see the [API reference](/docs/next/api/strings/useGT). --- ## Examples 1. Translating a string in a component ```jsx import { useGT } from 'gt-next/client'; export default function MyComponent() { const t = useGT(); return (

{t('Hello, world!')}

) } ```
```jsx export default function MyComponent() { return (

Hello, world!

) } ```
2. Translating a string with variables ```jsx import { useGT } from 'gt-next/client'; export default function MyComponent() { const t = useGT(); const count = 10; return (

{t('There are {count} items in the cart', { variables: { count } })}

) } ```
```jsx export default function MyComponent() { const count = 10; return (

There are {count} items in the cart

) } ```
3. Translating parts of an object ```jsx import { useGT } from 'gt-next/client'; export default function MyComponent() { const t = useGT(); const users = [ { name: 'John', description: t('John is a software engineer at General Translation'), }, { name: 'Jane', description: t('Jane is a software engineer at Google'), }, ] return (
{users.map((user) => (

{user.name}

{user.description}

))}
) } ```
```jsx export default function MyComponent() { const users = [ { name: 'John', description: 'John is a software engineer at General Translation', }, { name: 'Jane', description: 'Jane is a software engineer at Google', }, ] return (
{users.map((user) => (

{user.name}

{user.description}

))}
) } ```
4. Translating shared constants ```jsx copy title="src/llms.ts" import { useGT } from 'gt-next/client'; // Custom hook to get LLM data with translations export function useLLMData() { const t = useGT(); return [ { name: 'GPT-4.1', id: 'gpt-4.1', description: t('GPT-4.1 is a large language model developed by OpenAI'), }, { name: 'Claude 3.7 Sonnet', id: 'claude-3-7-sonnet', description: t('Claude 3.7 Sonnet is a large language model developed by Anthropic'), }, ] } ``` ```jsx import { useLLMData } from './llms'; export default function MyComponent() { const llms = useLLMData(); return (
{llms.map((llm) => (

{llm.name}

{llm.description}

))}
) } ```
```jsx copy title="src/llms.ts" export const llms = [ { name: 'GPT-4.1', id: 'gpt-4.1', description: 'GPT-4.1 is a large language model developed by OpenAI', }, { name: 'Claude 3.7 Sonnet', id: 'claude-3-7-sonnet', description: 'Claude 3.7 Sonnet is a large language model developed by Anthropic', }, ] ``` ```jsx import { llms } from './llms'; export default function MyComponent() { return (
{llms.map((llm) => (

{llm.name}

{llm.description}

))}
) } ```
**Be careful!** In this last example, you have to be very careful about how you use the `useGT()` hook. Make sure that it doesn't violate the [rules of React](https://react.dev/reference/rules/rules-of-hooks). Additionally, make sure that the `useGT()` hook is called within the React context. If your constants are defined outside of a React component, you will likely need to create a custom hook to access your data with translations. This is because the `useGT()` hook requires access to the React context of the component that is calling it. This context includes information about the current language and the translations for the current language. If you try to import the `llms` array directly, without knowing the current language, you will not be able to translate the strings. --- ## Common Pitfalls ### Translating Dynamic Content All strings must be known at build time. This means that you cannot translate dynamic content that is generated or retrieved at runtime. This includes variables, even if they are strings. ```jsx export default function MyComponent() { const [dynamicContent, setDynamicContent] = useState('Hello, world!'); const t = useGT(); return (

{t(dynamicContent)}

{/* This will not work */}
) } ``` If you need to translate dynamic content, read our guide on how to [translate content on-demand](/docs/next/guides/dynamic-content). This only works on Next.js server components. The CLI tool will warn you if you try to translate dynamic content with the `useGT()` hook. --- ## Next Steps * Learn about how to [translate JSX content on-demand](/docs/next/guides/dynamic-content). * Learn more about the [`` component](/docs/next/guides/jsx). * See the [API reference for `useGT()`](/docs/next/api/strings/useGT). # gt-next: General Translation Next.js SDK: Using Variables URL: https://generaltranslation.com/en/docs/next/guides/variables.mdx --- title: Using Variables description: How to use variable components --- ## Overview Variable components in `gt-next` allow you to insert dynamic content into translations. These components include: - [``](/docs/next/api/components/var): For rendering variables. - [``](/docs/next/api/components/num): For formatting numbers. - [``](/docs/next/api/components/currency): For formatting currency values. - [``](/docs/next/api/components/datetime): For formatting dates and times. In this guide, we will cover: What are variable components? How to use variable components Examples Common pitfalls ## What are variable components? Variable components are used to wrap dynamic content such as user names, numerical values, dates, and currencies. These components allow you to format and render dynamic values in a way that aligns with your user's locale, without requiring any external translations. Use variable components in conjunction with the `` component to ensure that dynamic content is displayed accurately and consistently. Each variable component has different behavior: - [``](/docs/next/api/components/var): Renders any content dynamically, such as user names or identifiers. - [``](/docs/next/api/components/num): Formats numerical values according to locale-specific rules. - [``](/docs/next/api/components/currency): Formats currency values with symbols and localization rules. - [``](/docs/next/api/components/datetime): Formats dates and times using locale-specific conventions. While JSX content and strings are translated via the General Translation API, variable components are completely handled locally. The ``, ``, and `` components use the [JS i18n API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) to format the content according to the user's locale. Content wrapped in variable components is never sent to the General Translation API, ensuring data privacy and security. See the section on [Data Privacy](#privacy) for more information. --- ## How to use variable components ### Basic Usage The usage for all variable components is the same. ```tsx const user = { name: 'John', age: 30, balance: 1000, birthday: new Date('1990-01-01'), }
{user.name} {user.age} {user.balance} {user.birthday}
``` Simply wrap the variable component around the content you want to display. ### Using Variable Components in `` [#variable-in-t] By themselves, variable components don't do much, since they require knowledge of the user's locale to format the content. Thus, you should use variable components with `` components. The `` component will not only handle the translation of the surrounding content, but also pass the correct locale to its child variable components. ```tsx The current time is {time}. ``` ### Variable localization [#localization] The ``, ``, and `` components include built-in localization support. These components automatically format their content based on your user's selected locale, or based on additional options passed as props. For example: * [``](/docs/next/api/components/num) displays numbers with localized decimal separators. * [``](/docs/next/api/components/currency) displays values with localized currency symbols and positioning. * [``](/docs/next/api/components/datetime) displays dates and times according to locale-specific rules. You can also override the default locale and formatting options by passing props directly to these components. ### Data Privacy [#privacy] Variable components handle all formatting locally; therefore, none of their children are sent to the General Translation APIs for translation (when used with `` components). This is perfect for keeping sensitive data, such as user names or account numbers, private and secure. Each variable component handles formatting differently and should be used for specific types of content: * [``](/docs/next/api/components/var): Anything private that does not require formatting - User names, account numbers, etc. * [``](/docs/next/api/components/num): Private numerical values that should be formatted according to locale - Order quantities, age, distance, etc. * [``](/docs/next/api/components/currency): Private currency values that should be formatted according to locale - Transaction amounts, account balances, etc. * [``](/docs/next/api/components/datetime): Private date and time values that should be formatted according to locale - Account creation dates, order timestamps, etc. [Branching Components](/docs/next/guides/branches) and [`` components](/docs/next/guides/jsx) do send data to the General Translation APIs for translation. Additionally, nesting a `` inside a `` component will send the content to the General Translation APIs for translation. ```tsx Hello, World! Goodbye, World! ``` In the example above, "Hello, World!" will be sent to the General Translation APIs for translation, while "Goodbye, World!" will not. --- ## Examples ### `` Because the `` component does not do any formatting, it should always be used in conjunction with a `` component. ```jsx import { T, Var } from 'gt-next'; export default function UserGreeting({ user }) { return ( Hello, {user.name}! Your address is {user.addr} ); } ``` Variable components also isolate data, so they can be used to render dynamic content that is not part of a translation. ```jsx import { T, Var } from 'gt-next'; export default function Dashboard({ isAdmin }) { return ( Your Dashboard: {isAdmin ? : } ); } ``` In the example above, the `isAdmin` ternary operator makes the `Dashboard` component dynamic. Without the ``, component, this would be an invalid use of the `` component. When using `` components with dynamic content, use `` to wrap anything dynamic! ### `` The `` component can be used as a child of a `` component or as a standalone component. ```jsx import { T, Num } from 'gt-next'; import { Badge } from '@components/custom/cart/Badge'; export default function OrderSummary() { const quantity = 10; return ( <> You have {quantity} items in your cart. {quantity} // This is the same as using quantity.toLocaleString() ); } ``` ### `` The `` component can be used as a child of a `` component or as a standalone component. ```jsx import { T, Currency } from 'gt-next'; import { Badge } from '@components/custom/cart/Badge'; export default function OrderSummary() { const total = 1000; return ( <> Your total is {total}. {total} // This will be formatted as $1,000 ); } ``` ### `` The `` component can be used as a child of a `` component or as a standalone component. ```jsx import { T, DateTime } from 'gt-next'; export default function OrderSummary() { const date = new Date(); return ( Your order was placed on {date}. {date} // This is the same as using date.toLocaleDateString() or date.toLocaleTimeString() ); } ``` --- ## Common Pitfalls ### Ignoring Localization Options [#localization-options] For ``, make sure to pass the `currency` prop to specify the currency type. This ensures that the correct currency symbol and formatting are used when displaying the value. Other components, such as `` and ``, also have optional props that allow you to customize the formatting as well. --- ## Notes * Variable components isolate data, so they can be used to render dynamic content that is not part of a translation. * Variable components do not send data to the General Translation APIs, so they are perfect for keeping sensitive data private and secure. * Variable components can be used either as a child of a [``](/docs/next/guides/jsx) component or as a standalone component. ## Next Steps * Explore conditional logic in [Branching Components](/docs/next/guides/branches). * Learn more about formatting options for specific variable components in the API Reference: - [``](/docs/next/api/components/num) - [``](/docs/next/api/components/currency) - [``](/docs/next/api/components/datetime) - [``](/docs/next/api/components/var) # gt-next: General Translation Next.js SDK: Deploy to Production URL: https://generaltranslation.com/en/docs/next/tutorials/quickdeploy.mdx --- title: Deploy to Production description: Let's deploy your Next.js app with GT. --- ## Overview This is a short tutorial to help you deploy your Next.js app with GT. In total, this should take less than 5 minutes to complete. We will do this in 3 steps: Add your production API keys. Run the `gtx-cli configure` command to configure your project. Add the translate command to your build script. ## Prerequisites We'll assume that you have already setup your Next.js app with GT. If you haven't, first setup your project by following the [Quick Start Guide](/docs/next/tutorials/quickstart). ## Step 1: Add your production API keys 🔑 To deploy your app to production, you'll need to use a production API key. From your [dashboard](https://generaltranslation.com/dashboard), go to **API Keys** in the sidebar. Click on **Create API Key**, and add them to your production envrionment. ```bash copy GT_API_KEY="YOUR_GT_API_KEY" GT_PROJECT_ID="YOUR_GT_PROJECT_ID" ``` **Protect Your API Keys!** Production keys should **only** ever be used in production. Likewise, development keys should **only** ever be used in development. *Never commit your API keys to a public repository!* ## Step 2: Run the `gtx-cli configure` command 🔧 If you've previously run the Setup Wizard, you can skip this step. The setup wizard will have already run the `gtx-cli configure` command for you. Run the `gtx-cli configure` command to configure your project. ```bash copy npx gtx-cli configure ``` If you do not want your translations to be hosted on the GT CDN, select "No" when asked. You will also need to configure the [`loadTranslations()`](/docs/react/api/config/load-translations) function. ## Step 3: Add the translate command to your build script 🏗️ The last step is to add the [translate command](/docs/cli/translate) to your build script. Make sure that the translate command comes before the build command. ```json title="package.json" copy { "scripts": { "build": "npx gtx-cli translate && <...YOUR_BUILD_COMMAND...>" } } ``` That's it! Now, when you deploy your app to production and run `npm run build`, your project will be automatically translated and deployed alongside your app. --- ## Next steps * See the [CLI docs](/docs/cli) for more information on the CLI tool. * Learn about the different configuration options for the CLI tool [here](/docs/cli/configure). * Read about the difference between production and development environments [here](/docs/react/concepts/environments). # gt-next: General Translation Next.js SDK: Next.js Quickstart URL: https://generaltranslation.com/en/docs/next/tutorials/quickstart.mdx --- title: Next.js Quickstart description: Easily internationalize your Next.js App with gt-next --- ## Overview This quickstart guide will walk you through how to setup your Next.js application with `gt-next`. By the end of this guide, you will have a Next.js app that is ready to start translating content. In this guide, we will cover the following: Installation Configuration Usage Testing Your App Deployment ### Prerequisites - A Next.js application using the App Router - Basic knowledge of Next.js and JavaScript ## Installation Install the `gt-next` and `gtx-cli` packages: ```bash npm i gt-next npm i --save-dev gtx-cli ``` ```bash yarn add gt-next yarn add --dev gtx-cli ``` ```bash bun add gt-next bun add --dev gtx-cli ``` ```bash pnpm add gt-next pnpm add --save-dev gtx-cli ``` --- **Automatic Setup:** We have an experimental Setup Wizard that can help you setup your project with `gt-next`. Try it out by running `npx gtx-cli@latest`. You'll still need to manually internationalize strings, but it will help you get started. See the [Setup Wizard](/docs/cli/init) reference guide for more information. Alternatively, if you would like your AI tool like Claude Code, Cursor, or Windsurf to automatically setup your project, you can use our [mcp server](/docs/platform/ai-tools). ## Configuration ### `withGTConfig` The `withGTConfig` function is a function that is used to initialize the SDK in a Next.js application. Place this in your `next.config.[js|ts]` file. ```tsx title="next.config.ts" import { withGTConfig } from 'gt-next/config'; const nextConfig = { // Your next.config.ts options }; export default withGTConfig(nextConfig, { // Additional GT configuration options }); ``` See the [withGTConfig API Reference](/docs/next/api/config/withGTConfig) for more information. ### `GTProvider` `gt-next` also exports a `GTProvider` component. This component is used to provide context to client-side components in your Next.js application. The `GTProvider` and `withGTConfig` work together to provide context to your application. This context includes: - Managing the user's current locale - The relevant translations for that locale - Context for the `useGT` hook - Context for the `useDict` hook First, add the `GTProvider` component to the root layout of your application. It should be placed as high up in your component tree as possible. ```tsx copy title="src/layout.tsx" import { GTProvider } from 'gt-next'; export default function RootLayout({ children }) { return ( {children} ); } ``` If you have multiple root layouts, place the `GTProvider` in each one. Next, create a [`gt.config.json`](/docs/cli/reference/config) file in the root of your project. This file is used to configure both the `gtx-cli` tool and the `gt-next` library. ```json title="gt.config.json" copy { "defaultLocale": "en", "locales": ["fr", "es"] } ``` You should customize the `defaultLocale` and `locales` to match your project. See the list of [supported locales](/docs/platform/locale-strings) for more information. `withGTConfig` will automatically detect the `gt.config.json` file in your project, and use it to configure the SDK. ### Environment Variables Set the following environment variables: ```bash copy GT_API_KEY="" # Your General Translation Developer API key GT_PROJECT_ID="" # Your General Translation project ID ``` **Make sure your API key variable is only set in your development environment! It should not be set in production.** You can get a free API key and project ID by creating a [General Translation account](https://dash.generaltranslation.com/signup). After creating an account, navigate to the [Development API Keys](https://dash.generaltranslation.com/settings/dev-api-keys) page to get your Dev API key and project ID. Alternatively, you can also use the CLI tool command [`npx gtx-cli auth`](/docs/cli/auth) to generate an API key and project ID for your project, saved to your `.env.local` file. `gt-next` is an i18n library that can work standalone without any environment variables. Without them, the library will act very similarly to other i18n libraries, and will still have core internationalization functionality. However, `gt-next` also offers a native integration with the General Translation platform. This integration unlocks additional functionality in the library, such as: - Translation Hot Reloading in Development - Automatic AI translations - Syncing translations with the General Translation platform - Native integration with our translation CDN - On-demand translation of React components in production (on the server side) To avoid using the General Translation platform, just don't set any environment variables. --- ## Usage Great! If you've followed the steps above, your Next.js app is now setup to use `gt-next`. The next step is to internationalize your content. Here, we'll give a brief overview of the different ways to translate content in your application. ### `` Component The `` component is the main component for translating JSX content in your application. To use it, simply wrap the JSX you want to translate in the `` component. ```tsx import { T } from 'gt-next';
Your content
``` If you have dynamic content, you'll need to use [variable components](/docs/next/guides/variables) to pass in the dynamic values. ```tsx import { T, Var } from 'gt-next';
Hello, {name}!
``` See the [Translating JSX](/docs/next/guides/jsx) guide for more information. ### `useGT` Hook The `useGT` hook is a React hook that returns a function that can be used to translate strings. ```tsx import { useGT } from 'gt-next/client'; const translate = useGT(); translate('Hello, world!'); ``` The `useGT` hook is a client-side hook, and should only be used in client-side components. For server-side components, use the async `getGT()` function instead. See the [Translating Strings](/docs/next/guides/strings) guide for more information. Utilizing the hot-reload translation functionality will be helpful for internationalizing your application. To enable this, make sure you have the `GT_API_KEY` and `GT_PROJECT_ID` environment variables set in your development environment. --- ## Testing Your App Congratulations! 🥳 If you've followed the steps above, your app is now multilingual! Let's see it in action. ### See Your App in a Different Language Add the [``](/docs/next/api/components/localeSelector) component to your app. This will allow you to select a different language for your app. **Tip:** You can also skip this step and just change your language in your browser settings. Start your Next.js app in development mode. ```bash npm run dev ``` ```bash yarn run dev ``` ```bash bun run dev ``` ```bash pnpm run dev ``` Open up your app in your preferred browser (usually at [http://localhost:3000](http://localhost:3000)). ### Troubleshooting **Browser Cookies** If you are deciding to test different languages by changing your browser's language, this issue may occur. Check your browser's cookies for your app. General translation uses cookies to store the user's language preference. The cookie is called `generaltranslation.locale`, and all you need to do is delete it. Then, just double check you are using the desired perferred language and then refresh the page. How to check cookies: * [Chrome](https://support.google.com/chrome/answer/95647) * [Firefox](https://support.mozilla.org/en-US/kb/delete-cookies-remove-info-websites-stored) * [Safari](https://support.apple.com/en-mn/guide/safari/sfri11471/16.0/mac/11.0) * [Edge](https://support.microsoft.com/en-us/microsoft-edge/delete-cookies-in-microsoft-edge-63947406-40ac-c3b8-57b9-2a946a29ae09) **On-Demand Translation** You may notice when loading languages in development, translations will take a few seconds to be displayed. This happens because your app is being translated in real time. We refer to this process as an "on-demand translation". This **only happens in dev** so you can easily prototype your website in different languages. All translations are preloaded in production, so there will be no delay. Follow our guide on [shipping to production](/docs/next/tutorials/quickdeploy). **JSX Translation** Right now, the wizard automatically adds `` components around text content. We are currently working on a solution that automatically setup string translations. Until then, if you are rendering a string, please follow [this guide](/docs/next/guides/strings) for translating strings. The most likely cause of an inaccurate translation is ambiguous wording. For example, "apple" can be a fruit or a technology company. To fix this, you can provide more context to the translation with the `context` prop. The [``](/docs/next/api/components/t), [`useGT()`](/docs/next/api/strings/useGT), and [`getGT()`](/docs/next/api/strings/getGT) functions all support a `context` prop. For example: ```jsx Apple ``` --- ## Deployment Great! If you're satisfied with your translations and the functionality of your app, you can now deploy your application. The behavior of `gt-next` in production is slightly different from development. Specifically, no translations will be performed at runtime (with the exception of the `` component & `tx` function). This means that you'll need to translate your content before deploying your application, in the build process. Luckily, the `gtx-cli` tool has a `translate` command that can be used to automatically translate your content. First, you'll need to get a Production API key from the [General Translation platform](https://dash.generaltranslation.com). Please note that this key is different from your Development API key, and begins with `gtx-api-`, instead of `gtx-dev-`. Read about the difference between Development and Production keys [here](/docs/next/concepts/environments). Add this environment variable to your CI/CD pipeline. ```bash GT_PROJECT_ID= GT_API_KEY= ``` Make sure that `GT_API_KEY` is **NOT** prefixed with `NEXT_PUBLIC_`! If it is, you'll risk exposing your API key to the public. Run the `translate` command to translate your content. ```bash npx gtx-cli translate ``` You can configure the behavior of the `translate` command with the [`gt.config.json`](/docs/cli/reference/config) file. See the [CLI Tool](/docs/cli/translate) reference guide for more information. Add the `translate` command to your build process. ```json title="package.json" copy { "scripts": { "build": "npx gtx-cli translate && <...YOUR_BUILD_COMMAND...>" } } ``` If you're not using the General Translation platform, you can still use `gt-next` in production. However, you'll need to manually translate your content before deploying your application. Instead of running `translate`, run the `generate` command to generate JSON files containing all of your translation data (in your source language). ```bash npx gtx-cli generate ``` Then, you'll need to manually edit / translate these files, and load them into your application with [`loadTranslations`](/docs/next/guides/local-tx). --- ## Summary * In this guide, we covered how to setup your Next.js app with `gt-next` * We briefly covered the different ways to translate content in your application. * We also covered how to deploy your application after you've internationalized your content. ## Next Steps - Learn about how to translate JSX content with the `` component: [Translating JSX](/docs/next/guides/jsx) - Learn about how to translate strings with the `useGT` hook: [Translating Strings](/docs/next/guides/strings) - Learn how to use local translations: [Local Translations](/docs/next/guides/local-tx) # gt-next: General Translation Next.js SDK: Translating Strings URL: https://generaltranslation.com/en/docs/next/tutorials/translating-strings.mdx --- title: Translating Strings description: How to translate strings --- ## Overview This guide is a step by step tutorial on how to translate strings in your Next.js app using [`useGT()`](/docs/next/api/strings/useGT), [`getGT()`](/docs/next/api/strings/getGT), and [`tx()`](/docs/next/api/strings/tx). ## Prerequisites We assume that you already have installed `gt-next` in your project and have followed or are currently following the [Quick Start Guide](/docs/next/tutorials/quickstart). ## Translating Strings ### Client Side Components For any client side strings, use [`useGT()`](/docs/next/api/strings/useGT). Remember that `useGT()` must be called within a child component of [``](/docs/next/api/components/gtprovider). ```jsx title="src/components/MyComponent.jsx" copy import { useGT } from 'gt-next/client'; export default function MyComponent() { const t = useGT(); // [!code highlight] return (

{t('This is a string that gets translated')}

// [!code highlight]
); } ``` ### Server Side Components For any server side strings, use [`getGT()`](/docs/next/api/strings/getGT). ```jsx title="src/pages/index.jsx" copy import { getGT } from 'gt-next/server'; export default async function Home() { const t = await getGT(); // [!code highlight] return (

{t('This is a string that gets translated')}

// [!code highlight]
); } ``` **Note:** When in development, if you are translating content at runtime, you will have to refresh the page to see the translated version of a string from [`getGT()`](/docs/next/api/strings/getGT). **This does not happen in production.** ### Adding Variables Variables are values that may change, but do not get translated. To add variables to your strings, use the following pattern: ```jsx title="MyComponent.jsx" copy import { useGT } from 'gt-next/client'; export default function MyComponent() { const t = useGT(); return (

{t('Hello there, {username}', { variables: { username: 'Brian123' }})}

// [!code highlight]
); } ``` This works with both [`useGT()`](/docs/next/api/strings/useGT) and [`getGT()`](/docs/next/api/strings/getGT). ### Dynamic Content Say that you have a string that changes. You can use the [`tx()`](/docs/next/api/strings/tx) function to translate the string at runtime. ```jsx title="MyComponent.jsx" copy import { tx } from 'gt-next/server'; export default async function MyComponent({ username }) { const translation = await tx(`Hello, ${username}. How is your day?`); // [!code highlight] return (

{translation}

// [!code highlight]
); } ``` **Note:** The [`tx()`](/docs/next/api/strings/tx) function is only available on the server side, and should only be used when necessary. Runtime translation often creates a delay. Use [`getGT()`](/docs/next/api/strings/getGT) or [`useGT()`](/docs/next/api/strings/useGT) whenever possible to translate before deployment. --- ## Notes * For translating strings, use [`useGT()`](/docs/next/api/strings/useGT), [`getGT()`](/docs/next/api/strings/getGT), and [`tx()`](/docs/next/api/strings/tx). * `useGT()` and `getGT()` translate before deployment, whereas `tx()` translates at runtime. Use `tx()` sparingly. * Variables can be added to strings using the `{ variables: { key: value } }` pattern. ## Next Steps * Return to the [Quick Start Guide](/docs/next/tutorials/quickstart) to finish setting up your project for translation. * See the API reference for [`useGT()`](/docs/next/api/strings/useGT), [`getGT()`](/docs/next/api/strings/getGT), and [`tx()`](/docs/next/api/strings/tx). # General Translation Platform: Automatic Translation URL: https://generaltranslation.com/en/docs/platform/features/files.mdx --- title: Automatic Translation description: Automatically translate your project files with General Translation. --- ## Overview General Translation provides powerful tools to translate entire files in your project directly through the CLI. This allows you to translate: - **JSON Files**: Translate your i18n JSON files for any library including next-intl, i18next, or custom JSON formats - **Markdown/MDX Files**: Translate your documentation or content files while preserving all formatting and structure - **TypeScript/JavaScript Files**: Translate strings in your code files without affecting their functionality With the GT CLI tool, you can translate entire directories of files with a single command, making it easy to localize your entire project. ## Supported File Types General Translation supports the following file types: | File Type | Description | |-----------|-------------| | `json` | JSON files used by i18n libraries like next-intl, i18next, etc. | | `mdx` | Markdown component files used for documentation | | `md` | Standard markdown files | | `js` | JavaScript files | | `ts` | TypeScript files | | `gt` | GT-specific translation files used by gt-next and gt-react | ## How It Works 1. Install the GT CLI tool: `npm install --save-dev gtx-cli` 2. Configure your project with the `gt.config.json` file 3. Run `npx gtx-cli translate` to automatically translate all specified files That's it! No need to wait days for translations, just run a command and get your translations in minutes. ## Benefits - **Maintain Context**: Files are translated as a whole, preserving context and improving translation quality - **Preserve Structure**: All formatting, code structure, and syntax are preserved in translated files - **Automation**: Integrate with CI/CD pipelines to automate translation in your workflow - **Multi-format Support**: Translate different file types with a single configuration - **i18n Library Compatibility**: Works with any i18n library or custom format # General Translation Platform: Hot Reload URL: https://generaltranslation.com/en/docs/platform/features/hot-reload.mdx --- title: Hot Reload description: Hot reload your translations in development with General Translation. --- ## Overview Translation Hot-Reloading allows you to: - See what your content looks like in different languages in real-time. - Fix CSS issues early in development. - Perfect your UI so that it looks and feels just right for every language. import Video from '@/components/Video';