DocsQuickstarts

Quickstart - Next.js App Router

Add Generic Translation to a Next.js App Router project with locale-prefixed routes, server components and a translation file written by the CLI.

On this page

This walkthrough adds Spanish and French to a Next.js App Router app (Next 14 or newer, React 18 or newer). You will wrap the config, add the middleware, mount the provider in the root layout, mark up some text, and run the CLI.

1. Install

The Generic Translation packages are not published to npm yet. Until they are, build them from source. Clone the parent repository, build @generic-translation/core, @generic-translation/react and the generic-translation CLI there, and link them into your app. See the Introduction for the repository layout.

git clone --recurse-submodules https://github.com/generic-translation/generic-translation.git
# build each package once (pnpm is used throughout this repo)
for p in core react cli; do (cd generic-translation/packages/$p && pnpm install && pnpm build); done

Then, in your Next.js app, reference the built packages with link: paths in package.json and install:

{
  "dependencies": {
    "@generic-translation/core": "link:../generic-translation/packages/core",
    "@generic-translation/react": "link:../generic-translation/packages/react"
  },
  "devDependencies": {
    "@generic-translation/cli": "link:../generic-translation/packages/cli"
  }
}
pnpm install

Each package is also in its own public repository (generic-translation-core, generic-translation-react, generic-translation-cli under github.com/JacobFV). Installing straight from GitHub only works if the dist/ folder is present in what gets fetched, so the clone-and-link route above is the one that is known to work.

2. Create the config and a project

pnpm generic-translation init --locales es,fr

generic-translation init detects the framework (next-app), writes generic-translation.config.json, and can create a project for you through the API when you are logged in (--create-project). It writes GENERIC_TRANSLATION_PROJECT_ID and GENERIC_TRANSLATION_API_KEY to .env.local and adds that file to .gitignore. See the CLI reference for every flag and the config reference.

You can also create the project and API key in the dashboard and put them in .env.local yourself:

# .env.local  (never commit this file, never expose the key to the browser)
GENERIC_TRANSLATION_PROJECT_ID=prj_...
GENERIC_TRANSLATION_API_KEY=gt-api-...

A resulting generic-translation.config.json looks like this:

{
  "projectId": "prj_...",
  "defaultLocale": "en",
  "locales": ["es", "fr"],
  "src": ["src/**/*.{ts,tsx,js,jsx}", "app/**/*.{ts,tsx,js,jsx}"],
  "output": "public/_generic-translation/[locale].json"
}

3. Wrap the Next config

// next.config.mjs
import { withGenericTranslation } from "@generic-translation/react/next/config";

export default withGenericTranslation({ reactStrictMode: true });

withGenericTranslation reads generic-translation.config.json and exposes the locales and project id as NEXT_PUBLIC_GENERIC_TRANSLATION_* variables. It never forwards GENERIC_TRANSLATION_API_KEY and throws if your config tries to inline one. Details in Next.js setup.

4. Add the middleware

// middleware.ts
import { createGenericTranslationMiddleware } from "@generic-translation/react/next/middleware";

export default createGenericTranslationMiddleware({ locales: ["es", "fr"], defaultLocale: "en" });

export const config = { matcher: ["/((?!api|_next|_generic-translation|.*\\..*).*)"] };

With the defaults (localePrefix: "as-needed"), English lives at /about and the others at /es/about and /fr/about. The middleware rewrites internally to /{locale}/..., so your routes go under app/[locale]/. See the middleware page for the other modes.

5. Root layout under app/[locale]

// app/[locale]/layout.tsx
import type { ReactNode } from "react";
import { GenericTranslationProvider, setRequestLocale } from "@generic-translation/react/next";

export function generateStaticParams() {
  return [{ locale: "en" }, { locale: "es" }, { locale: "fr" }];
}

export default async function RootLayout({
  children,
  params,
}: {
  children: ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  setRequestLocale(locale);
  return (
    <html lang={locale}>
      <body>
        <GenericTranslationProvider locale={locale}>{children}</GenericTranslationProvider>
      </body>
    </html>
  );
}

Passing locale explicitly keeps the pages statically renderable, because nothing has to read request headers. The server GenericTranslationProvider loads the translation map for the locale and hands it to the client provider so the first paint is already translated.

6. Mark up text

A server component:

// app/[locale]/page.tsx
import { T, Var, Plural, setRequestLocale } from "@generic-translation/react/next";

export default async function Home({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  setRequestLocale(locale);
  const unread = 3;
  return (
    <main>
      <h1>
        <T>Welcome to <strong>Acme</strong></T>
      </h1>
      <p>
        <T>
          You have <Plural n={unread} one="one unread message" other={<><Var>{unread}</Var> unread messages</>} />.
        </T>
      </p>
    </main>
  );
}

A client component imports from @generic-translation/react instead:

"use client";
import { T, LocaleSelector } from "@generic-translation/react";

export function Header() {
  return (
    <header>
      <T>Dashboard</T>
      <LocaleSelector />
    </header>
  );
}

Server components use the @generic-translation/react/next entry point (the async <T>); client components use @generic-translation/react. See Server components.

7. Translate

pnpm generic-translation translate

This extracts every message from src and app, sends the new ones to the API, waits for the job, and writes public/_generic-translation/es.json and public/_generic-translation/fr.json. Re-running only sends changes. Run pnpm dev and visit /es.

To serve translations from the CDN instead of local files, publish them (generic-translation translate --publish, or set "publish": true in the config). The server then falls back to https://generic-translation-api.jacobfv123.workers.dev/cdn/{projectId}/{locale}.json when no local file exists. See Publishing and the CDN.

Next

Something wrong or unclear on this page? Open an issue.

Type to search the documentation.