Next.js Server-Side Rendering

AutoLocalise provides comprehensive SSR support for Next.js applications with automatic locale detection and server-side translation. This guide covers the modern approach using the withServerTranslation HOC.

Key Benefits

  • SEO-Optimized: Search engines see fully translated content on first load
  • Dynamic Locale Support: Automatically handles any language without pre-configuration
  • Fast Performance: Efficient server-side caching reduces API calls
  • Clean URLs: Locale-specific URLs like /zh/about, /fr/contact

Prerequisites

npm install react-autolocalise

1. Middleware Setup

Create a middleware file to detect user's locale and set up dynamic routing:

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

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Skip middleware for API routes, static files, and Next.js internals
  if (
    pathname.startsWith("/api") ||
    pathname.startsWith("/_next") ||
    pathname.includes(".")
  ) {
    return NextResponse.next();
  }

  // Get locale from accept-language header
  const acceptLanguage = request.headers.get("accept-language");
  const browserLocale = acceptLanguage?.split(",")[0]?.split("-")[0] || "en";

  // Redirect root to locale-specific URL
  if (pathname === "/") {
    return NextResponse.redirect(new URL(`/${browserLocale}`, request.url));
  }

  // If path doesn't start with a locale, redirect to add locale
  const pathSegments = pathname.split("/");
  const firstSegment = pathSegments[1];

  // Simple check: if first segment is not a 2-letter code, add locale
  if (!firstSegment || firstSegment.length !== 2) {
    return NextResponse.redirect(
      new URL(`/${browserLocale}${pathname}`, request.url)
    );
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};

2. Server Component Implementation

Dynamic Locale from URL

The most common pattern for multilingual sites:

// app/[locale]/page.tsx
import { withServerTranslation } from "react-autolocalise/server";

const config = {
  apiKey: "your-api-key",
  sourceLocale: "en", // Your app's original language
};

// Clean HOC approach - automatically uses locale from props
const HomePage = withServerTranslation(config, ({ t, tf, locale }) => (
  <div>
    <h1>{t("Welcome to our app")}</h1>
    <p>{t("This content is automatically translated")}</p>
    {tf(
      <>
        Experience <strong>powerful</strong> and <em>reliable</em> translations!
      </>
    )}
    <p>Current language: {locale}</p>
  </div>
));

export default async function Page({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  return <HomePage locale={locale} />;
}

Fixed Target Language

For apps targeting a specific market:

// For apps targeting a specific language (e.g., Spanish market)
const config = {
  apiKey: "your-api-key",
  sourceLocale: "en",
  targetLocale: "es", // Always translate to Spanish
};

const Page = withServerTranslation(config, ({ t, tf }) => (
  <div>
    <h1>{t("Welcome to our app")}</h1>
    <p>{t("All content will be in Spanish")}</p>
    {tf(
      <>
        Built for <strong>Spanish</strong> speaking users!
      </>
    )}
  </div>
));

export default Page;

3. SEO Metadata Generation

Generate translated metadata for better SEO:

// app/[locale]/layout.tsx
import { translateServerStrings } from "react-autolocalise/server";

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

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;

  const strings = [
    "My Awesome App - Best Solution for Your Business",
    "Discover the most powerful tools to grow your business online",
  ];

  const translations = await translateServerStrings(strings, locale, config);

  return {
    title: translations["My Awesome App - Best Solution for Your Business"],
    description:
      translations[
        "Discover the most powerful tools to grow your business online"
      ],
  };
}

4. Component Features

Translation Function (t)

const MyComponent = withServerTranslation(config, ({ t }) => (
  <div>
    <h1>{t("Simple translation")}</h1>
    <p>{t("Dynamic content with variables").replace("{{name}}", userName)}</p>
  </div>
));

Formatted Translation (tf)

Preserves nested formatting while translating:

const FormattedComponent = withServerTranslation(config, ({ tf }) => (
  <div>
    {tf(
      <>
        Welcome to our <strong>amazing</strong> platform with{" "}
        <em>powerful features</em>!
      </>
    )}
  </div>
));

5. Best Practices

Performance Optimization

  • Batch translations: Group related text together in components
  • Cache configuration: Set appropriate cacheTTL in your config
  • Avoid over-nesting: Keep component hierarchy simple for better performance

SEO Optimization

  • Use semantic HTML: Ensure translated content maintains proper structure
  • Generate sitemaps: Include all locale-specific URLs
  • Set proper lang attributes: Use locale information in HTML

Development Tips

  • Environment variables: Store API keys securely
  • TypeScript: Use proper typing for locale parameters

Next Steps