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:
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.
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.
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.
Setting Up the Root Layout
Modify the layout.tsx
file to handle dynamic loading of translations based on the user's selected locale:
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:
Localizing Client Components
For client-side components, use the useTranslations hook: