LogoGalsenext
Guide et Tutoriel

Internationalisation

---

Internationalization (i18n) and Providers Configuration

Galsenext is configured to support internationalization (i18n), authentication, themes, and more. This section provides a detailed explanation on configuring the Providers and their usage to get the application up and running.

Providers Configuration

In Galsenext, several providers are used for managing global state, user sessions, themes, and translations.

Here is the configuration of the Providers component:

Providers Component

The Providers component consolidates all the necessary providers for your Next.js application. It is often used in the _app.tsx file to wrap the application and provide the necessary contexts to all components.

Here is the configuration of the 'Providers' component:

Component Providers

"use client";
 
import { SessionProvider } from "next-auth/react";
import { ThemeProvider } from "next-themes";
import { PropsWithChildren } from "react";
import { Toaster } from "react-hot-toast";
import { AppProgressBar as ProgressBar } from "next-nprogress-bar";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProviderClient } from "@/locales/client";
 
const queryClient = new QueryClient();
 
export const Providers = (props: PropsWithChildren<{ locale: string }>) => {
  return (
    <>
      <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
        <SessionProvider>
          <Toaster />
          <ProgressBar
            height="3px"
            color="#FFA500"
            options={{ showSpinner: false }}
            shallowRouting
          />
          <QueryClientProvider client={queryClient}>
            <I18nProviderClient locale={props.locale}>
              {props.children}
            </I18nProviderClient>
          </QueryClientProvider>
        </SessionProvider>
      </ThemeProvider>
    </>
  );
};

Explanation of Used Providers

  • ThemeProvider: Manages the application themes (light or dark).
  • SessionProvider: Provides authentication features based on next-auth.
  • Toaster: Manages user notifications.
  • ProgressBar: A progress bar to indicate page loading.
  • QueryClientProvider: Manages client-side queries via react-query.
  • I18nProviderClient: Provides client-side internationalization features.

Integration into the Layout

To integrate these Providers into your application, you need to wrap them around your RootLayout component. Here is an example configuration for RootLayout:

File layout.tsx

import type { Metadata } from "next";
import "./globals.css";
import { Providers } from "./Providers";
 
export const metadata: Metadata = {
  title: "Galsenext",
  description: "Generated by create next app",
};
 
export default function RootLayout({
  children,
  params,
}: Readonly<{
  children: React.ReactNode;
  params: {
    locale: string;
  };
}>) {
  return (
    <html lang={params.locale}>
      <body>
        <Providers locale={params.locale}>{children}</Providers>
      </body>
    </html>
  );
}

Explanation

  • RootLayout: This component wraps the application and provides the necessary global context for the proper functioning of various features, including translations, themes, and sessions.

Internationalization (i18n) Configuration

For a multilingual application, configuring internationalization is essential.

Client-Side Configuration

The following code configures the client to support English and French translations:

"use client";
import { createI18nClient } from "next-international/client";
 
export const {
  useI18n,
  useScopedI18n,
  I18nProviderClient,
  useCurrentLocale,
  useChangeLocale,
} = createI18nClient({
  en: () => import("./en"),
  fr: () => import("./fr"),
});

Server-Side Configuration

The server uses createI18nServer for managing translations:

import { createI18nServer } from "next-international/server";
 
export const { getI18n, getScopedI18n, getStaticParams } = createI18nServer({
  en: () => import("./en"),
  fr: () => import("./fr"),
});

Usage Example

Here is an example of using a component with internationalization:

import { getAuthSession } from "@/src/lib/auth";
import Link from "next/link";
import Container from "@/components/elements/Container";
import { LayoutHeader, LayoutTitle } from "@/src/components/Layout/Layout";
import { getI18n } from "@/locales/server";
 
export type AuthenticatedContentProps = { session: any };
 
const AuthenticatedContent: React.FC<AuthenticatedContentProps> = async ({
  session,
}: any) => {
  const t = await getI18n();
  return (
    <Container>
      <div className="container">
        <LayoutHeader>
          <LayoutTitle>Home page</LayoutTitle>
          <h2>{t("new")}</h2>
        </LayoutHeader>
      </div>
    </Container>
  );
};
 
export default AuthenticatedContent;

Explanation

  • getI18n: Retrieves translations on the server side.
  • LayoutHeader and LayoutTitle: Layout components for the application's structure.
  • t("new"): Uses the translation function to display text in the current language.

Middleware Configuration for Internationalization (i18n)

For optimal language management in your application, Galsenext uses a dedicated middleware to redirect users to the appropriate language version based on their language preference or the application's default language.

Middleware i18n

import { createI18nMiddleware } from "next-international/middleware";
import { NextRequest } from "next/server";
 
const I18nMiddleware = createI18nMiddleware({
  locales: ["en", "fr"],
  defaultLocale: "en",
});
 
export function middleware(request: NextRequest) {
  return I18nMiddleware(request);
}
 
export const config = {
  matcher: ["/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt).*)"],
};

Explanation of the Middleware

  • createI18nMiddleware: This function generates middleware to handle internationalization in the Next.js application. It is configured with supported languages (locales) and the default language (defaultLocale).
  • middleware: This function is executed on every request, applying the language redirection middleware based on the user's language or the default language.
  • config: The middleware configuration specifies which routes it applies to, excluding APIs, static files, Next.js generated files, and other non-relevant resources.

Why Use This Middleware?

  • Automatic Redirection: Redirects users to their preferred language or the default language, providing a personalized user experience.
  • Centralized Language Management: Simplifies language management by concentrating language selection logic in one place.
  • Easy Multilingual Support: Makes your application easily adaptable for a global audience, ensuring that the right content is served to the right audience.

On this page