AutoLocalise SSR Support for Next.js

This guide provides step-by-step instructions for migrating your Next.js application to use AutoLocalise for automatic translations.

Installation

First, install the AutoLocalise SDK:

npm install react-autolocalise
# or
yarn add react-autolocalise

Client Side Rendering

The client side handling is same as React Implementation

Server-Side Rendering

AutoLocalise supports Next.js SSR through middleware and server components

1. Create a middleware file: To help us get the locale from the url or from the header

Note: Put the middleware.ts (or .js) in the root of your project to define Middleware. For example, at the same level as app or pages, or inside src if applicable. Refer Here

// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

const defaultLocale = "en";

export function middleware(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const localeParam = searchParams.get("locale");

  const acceptLanguage = request.headers.get("accept-language");
  const browserLocale = acceptLanguage
    ?.split(",")[0]
    .split(";")[0]
    .substring(0, 2);

  const locale = localeParam || browserLocale || defaultLocale;

  const response = NextResponse.next();
  response.headers.set("x-locale", locale);
  return response;
}

export const config = {
  matcher: "/:path*",
};

2. Initialize Translation Service (Singleton Pattern)

The SDK uses a singleton pattern for the TranslationService to ensure efficient caching and batch processing. Create a utility file to manage the translator instance:

// utils/translator.ts
import ServerTranslation from "react-autolocalise/server";

const config = {
  apiKey: "your-api-key",
  sourceLocale: "fr",
  targetLocale: "en",
};

// Simple function to get a translator instance
export function getTranslator() {
  return new ServerTranslation(config);
}

3. Server Component Implementation

Note: For server-side rendering, all translations must be completed before sending the response to the client. This requires a two-step process: first mark texts for translation using t() , then execute all translations in a single batch with execute() . This ensures all translations are ready before rendering occurs.

Basic Usage:

import { getTranslator } from "@/utils/translator";

async function ServerComponent() {
  const translator = getTranslator();

  // Mark texts for translation
  const title = translator.t("Hello from Server Component");
  const description = translator.t(
    "This component is rendered on the server side"
  );

  // Execute all translations in a single batch
  await translator.execute();

  // Get translated texts
  return (
    <div>
      <h1>{translator.get(title)}</h1>
      <p>{translator.get(description)}</p>
    </div>
  );
}

export default ServerComponent;

Use with nested text formatting:

For components with styled text, use tFormatted() and getFormatted() to preserve formatting:

import { getTranslator } from "@/utils/translator";

async function FormattedServerComponent() {
  const translator = getTranslator();

  // Mark formatted text with nested styling for translation
  const formattedContent = (
    <>
      Hello, we <span style={{ color: "red" }}>want</span> you to be{" "}
      <strong style={{ fontWeight: "bold" }}>happy</strong>!
    </>
  );
  // Mark the formatted texts for translation
  translator.tFormatted(formattedContent);

  // Also mark some regular text
  const subtitle = translator.t("Server-side nested formatting example");

  // Execute all translations in a single batch
  await translator.execute();

  return (
    <div>
      <h3>{translator.get(subtitle)}</h3>
      <p>{translator.getFormatted(formattedContent)}</p>
    </div>
  );
}

export default FormattedServerComponent;

For additional help, you can rise in our Github Page.