Clocale

Next.js

Prerequisites

Before starting, ensure you have:

  • An existing Next.js project
  • A plan for which languages your application will support

Installing Dependencies

First, add the Clocale package to your project:

npm install @clocale/react

This library provides the core functionality for handling translations in your React.js application.

Creating the Clocale Provider for Client Components

The ClocaleTranslationProvider is a React context provider that wraps your Next.js application. It initializes the Clocale library with the user's locale and server-side translations. This provider should be placed at the root of your application to ensure all components have access to translation functions.

'use client';

import { ClocaleProvider, SSRTranslations } from '@clocale/react';

interface ClocaleTranslationProvierProps {
  locale: string;
  children: React.ReactNode;
  ssrTranslations: SSRTranslations;
  isDev: boolean;
}
export const ClocaleTranslationProvider = ({
  children,
  locale,
  ssrTranslations,
  isDev,
}: ClocaleTranslationProvierProps) => {
  return (
    <ClocaleProvider
      type="server"
      locale={locale}
      ssrTranslations={ssrTranslations}
      isDev={isDev}
    >
      {children}
    </ClocaleProvider>
  );
};

Managing Locales with Cookies

This utility handles locale persistence using HTTP cookies. The getLocale function retrieves the user's preferred language from cookies, defaulting to 'en' if not set. The setLocale function updates the locale cookie when the user changes their language preference.

"use server";

import { cookies } from "next/headers";

const COOKIE_NAME = "locale";

export const getLocale = async () => {
  const cookieStore = await cookies();
  return cookieStore.get(COOKIE_NAME)?.value ?? "en";
};

export const setLocale = async (locale: string) => {
  const cookieStore = await cookies();
  cookieStore.set(COOKIE_NAME, locale);
};

Configuring the Clocale Client for Server Components

This configuration sets up the Clocale client for Next.js. The createServerClient function initializes the translation system with the current locale and API configuration. The builder function creates a new Clocale instance with the specified locale and API endpoint, enabling server-side translations in your application.

import { ClocaleNext, createServerClient } from "@clocale/react/next";

import { getLocale } from "./path/to/locale";

export const { getTranslation, getClocaleClient } = createServerClient({
  getLocale,
  builder: async (locale) =>
    ClocaleNext().init({
      locale,
      baseUrl: "your-project-integration-url",
    }),
});

Setting Up the Root Layout

Modify the layout.tsx file to handle dynamic loading of translations based on the user's selected locale:

import { getLocale } from './path/to/locale';
import { getClocaleClient } from './path/to/clocale';
import { ClocaleTranslationProvider } from '.path/to/ClocaleTranslationProviders';

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const locale = await getLocale();

  const clocaleClient = await getClocaleClient();

  // array of namespaces used in your project
  const translations = await clocaleClient.fetchTranslations(['test']);
  return (
    <html lang={locale}>
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased`}
      >
        <ClocaleTranslationProvider
          locale={locale}
          ssrTranslations={translations}
          isDev={true} // set value to false for production environment
        >
          {children}
        </ClocaleTranslationProvider>
      </body>
    </html>
  );
}

You can connect to the localization service for dynamic content translation using the baseUrl from your project's developer settings. This URL is essential for establishing a connection between your application and the Clocale service. Learn more

⚠️ Important: Only set isDev=true in development. Never enable this in production. Learn more

Localizing Server Components

For server components or server actions, use getTranslations to access localized content:

'use server';

import { getTranslation } from './path/to/clocale';

const Login = () => {
  const { t }= await getTranslation('auth.login'); // `auth` is the name of your namespace

  // `t` returns the translated string
  return (
    <div>
       <span>{t('title')}</span>
       <span>{t('description')}</span>
       <input 
          type="text" 
          placeholder={t("input.login")}
       />
    </div>
  );
}

Localizing Client Components

For client-side components, use the useTranslations hook:

'use client';

import { useTranslation } from '@clocale/react';

export const Dashboard = () => {
  const { t } = useTranslation('home.dashboard');

  // `t` returns the translated string
  return (
    <p>
      {t('page.description')}
    </p>
    <input 
        type="text" 
        placeholder={t("input.search")}
    />

  );
};

On this page