General Translation  
Next.jsTutorials

Translating Strings

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(), getGT(), and 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.

Translating Strings

Client Side Components

For any client side strings, use useGT(). Remember that useGT() must be called within a child component of <GTProvider>.

src/components/MyComponent.jsx
import { useGT } from 'gt-next/client';
 
export default function MyComponent() {
  const t = useGT(); 
  return (
    <div>
      <h1>{t('This is a string that gets translated')}</h1>
    </div>
  );
}

Server Side Components

For any server side strings, use getGT().

src/pages/index.jsx
import { getGT } from 'gt-next/server';
 
export default async function Home() {
  const t = await getGT(); 
  return (
    <div>
      <h1>{t('This is a string that gets translated')}</h1>
    </div>
  );
}

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(). 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:

MyComponent.jsx
import { useGT } from 'gt-next/client';
 
export default function MyComponent() {
  const t = useGT();
  return (
    <div>
      <h1>{t('Hello there, {username}', { variables: { username: 'Brian123' }})}</h1>
    </div>
  );
}

This works with both useGT() and getGT().

Dynamic Content

Say that you have a string that changes. You can use the tx() function to translate the string at runtime.

MyComponent.jsx
import { tx } from 'gt-next/server';
 
export default async function MyComponent({ username }) {
  const translation = await tx(`Hello, ${username}. How is your day?`); 
  return (
    <div>
      <h1>{translation}</h1>
    </div>
  );
}

Note: The tx() function is only available on the server side, and should only be used when necessary. Runtime translation often creates a delay. Use getGT() or useGT() whenever possible to translate before deployment.


Notes

  • For translating strings, use useGT(), getGT(), and 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

On this page