Translate a Next.js Pages application

Load a page's translated messages, render them through the Pages wrapper, and add locale switching and alternate links.

A Next.js Pages route already resolves a locale for its request. @lingo.dev/react-next uses that locale to supply React messages, keeping page data and translated text together. This recipe renders an About page in English and French and retains route selection when translated JSONC has lost its metadata.

Use an existing Pages application with React 19. The package declares Next.js 13+ and React 18/19 peers, but the current runtime provider uses React 19 context shorthand. Its exports are /pages, /pages/client, and /pages/server; it has no root export or App Router entry.

Configure locales and the app wrapper #

sh
npm install @lingo.dev/react@1.17.1 @lingo.dev/react-next@1.17.1
npm install @lingo.dev/spec@1.17.1 jsonc-parser
npm install --save-dev @lingo.dev/cli@latest

Add i18n to your existing next.config.mjs, retaining its other settings:

js
export default {
  i18n: { locales: ["en", "fr"], defaultLocale: "en" },
};

In pages/_app.tsx, wrap the application:

tsx
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
import { useEffect } from "react";
import { withLingoApp } from "@lingo.dev/react-next/pages/client";

function App({ Component, pageProps }: AppProps) {
  const { locale, defaultLocale } = useRouter();
  useEffect(() => {
    document.documentElement.lang = locale ?? defaultLocale ?? "en";
  }, [locale, defaultLocale]);
  return <Component {...pageProps} />;
}

export default withLingoApp(App);

The wrapper reads pageProps.__lingoMessages, resolves Next's active locale, and supplies LingoProvider. Next's own i18n settings determine the URL policy; the default English path is normally unprefixed.

Write the page and load its messages #

First add the loadMatchedMessages function from catalog loading as lib/catalog.ts. It validates string-valued JSONC and joins target values to active source keys.

Then create pages/about.tsx:

tsx
import { readFile } from "node:fs/promises";
import path from "node:path";
import type { GetStaticProps } from "next";
import { useLingo, type Messages } from "@lingo.dev/react";
import { loadMatchedMessages } from "../lib/catalog";

export const getStaticProps: GetStaticProps<{ __lingoMessages: Messages }> = async (ctx) => {
  const locale = ctx.locale ?? ctx.defaultLocale ?? "en";
  if (!["en", "fr"].includes(locale)) return { notFound: true };
  const source = await readFile(path.join(process.cwd(), "locales/en.jsonc"), "utf8");
  const target =
    locale === "en" ? source : await readFile(path.join(process.cwd(), "locales", `${locale}.jsonc`), "utf8");
  const messages = loadMatchedMessages(source, target, (entry) => {
    const route = entry.metadata.src?.replace(/\.\w+(?::\d+)?$/, "");
    return !route || route === "pages/about" || (!route.startsWith("pages/") && !route.startsWith("src/pages/"));
  });
  return { props: { __lingoMessages: messages } };
};

export default function About() {
  const l = useLingo();
  return <h1>{l.text("About us", { context: "About page heading" })}</h1>;
}

This predicate keeps the page's own entries plus shared component messages. It strips extensions and older line-number suffixes from source metadata. If the page lives at src/pages/about.tsx, update both the import path and the route comparison to match.

The custom loader deliberately fails when a required file is missing or malformed, so a build cannot silently replace the expected French catalog with English fallback. Missing individual target keys remain absent and use normal runtime fallback.

Extract, translate, and open both routes #

Run npx lingo extract --src pages --source-locale en from the project root. For a new Lingo.dev project configuration, run:

sh
npx lingo init --source en --targets fr --files 'locales/en.jsonc' --yes
npx lingo login
npx lingo link
npx lingo push --backfill-missing --wait

For an already configured project, preserve its binding and other file options. After extraction, complete ordinary updates for the existing target locales, retrieve and inspect them, then add fr and backfill without changing that source revision. Catalog loading gives the configuration steps, and Add a language explains the required order. If shared components live outside pages, extract from a directory containing all message calls, or organize them under a common src tree and use --src src.

After retrieving locales/fr.jsonc, run the normal Next development or build command. Open /about and /fr/about. The first uses the English source; the second uses the French target for the same heading key. Check the actual French text and the source fallback for a deliberately missing entry.

Built-in static-props loading #

When each locale file retains correct @src and @orphan metadata, the server helper can replace the custom getStaticProps above:

ts
import { withLingoProps } from "@lingo.dev/react-next/pages/server";

export const getStaticProps = withLingoProps({ route: "pages/about" });

withLingoProps({ route, handler? }) reads fixed locales/<locale>.jsonc paths relative to the working directory. It filters orphaned entries and other pages, treating non-page sources and entries without @src as shared. General JSONC translation retains @orphan marks but removes @src comments, so use the source-key join recipe above for that output; the helper does not restore metadata.

A missing file yields {} with a development warning; an invalid existing file can throw. An optional async handler adds props or returns a redirect/not-found result. Successful results retain fields such as revalidate and add __lingoMessages. Its public types use static-props context and results; do not assume arbitrary server-side request handlers have the same contract. CLI catalog-path overrides also do not change this fixed loader directory.

Expand dynamic static paths #

For a dynamic route, the server helper expands each parameter entry across Next's configured locales:

ts
import { withLingoPaths } from "@lingo.dev/react-next/pages/server";

export const getStaticPaths = withLingoPaths(async () => [{ params: { slug: "refund-policy" } }], {
  fallback: "blocking",
});

The default fallback is "blocking"; false and true are also supported. Expansion does not translate slugs or establish that every catalog contains the route's messages.

Switch language and add alternates #

Render a switcher beneath the app wrapper:

tsx
import { LingoHead, useLocaleSwitch } from "@lingo.dev/react-next/pages/client";

export function Languages() {
  const switchLocale = useLocaleSwitch();
  return (
    <nav aria-label="Language">
      <LingoHead baseUrl="https://example.com" />
      <button onClick={() => switchLocale("en")}>English</button>
      <button onClick={() => switchLocale("fr")}>Français</button>
    </nav>
  );
}

Replace the example origin with the site's absolute production origin. LingoHead emits alternates for configured locales and x-default, omitting the default-locale prefix. It does not emit canonical or Open Graph metadata. Inspect the resulting URLs for your route and query policy.

The switch callback writes NEXT_LOCALE for one year at / with SameSite=Lax, then navigates with Next's router using the current asPath. Supply configured locales, as above; it does not validate arbitrary input against the supported list.

Set initial document attributes #

Set the initial attributes in pages/_document.tsx, retaining any existing document customizations:

tsx
import Document, { Html, Head, Main, NextScript } from "next/document";
import { createLingo } from "@lingo.dev/react";

export default class LocalizedDocument extends Document {
  render() {
    const locale = this.props.__NEXT_DATA__.locale ?? "en";
    return (
      <Html lang={locale} dir={createLingo(locale).direction}>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

withLingoApp sets direction after locale changes and emits an inline RTL script for initial rendering, but it does not set lang. The _app effect above updates lang during navigation; the custom document supplies both initial attributes. A strict content-security policy can block the wrapper's inline script, and the wrapper exposes no nonce option. The custom document supplies initial direction without depending on that script. Check the application's script policy during navigation too.

Finally, check hydration with the same catalog and explicit time inputs. Verify a language switch changes the messages and document attributes together.