Localize Markdoc with Next.js

Route, load, translate, and render locale-specific Markdoc documents alongside separate UI catalogs in a Next.js App Router application.

A translated article needs to agree with the page around it. In a Next.js site, the route locale can choose both the Markdoc document and a separate UI catalog for navigation. This guide connects those files to an App Router page, then translates them through the CLI.

Use an existing Next.js App Router project with Markdoc. The example reads local files on the server and does not depend on a React localization adapter.

Choose a locale-specific file layout #

An illustrative project can keep documents and UI catalogs together by locale:

text
src/content/
  en/
    pages/home.mdoc
    blog/welcome.mdoc
    ui.json
  es/
    pages/home.mdoc
    blog/welcome.mdoc
    ui.json
src/app/[lang]/

Keep slugs stable when they are content identifiers. A translated heading need not rename home.mdoc. If you deliberately localize slugs, maintain an explicit mapping for navigation and alternate-language links; translating the body does not create that mapping.

Keep the route locale and document slug within known sets before constructing a filesystem path. Choose a missing-translation policy: a not-found response or an explicit source-language fallback. The homepage example below uses a fixed document name and returns not found for unsupported locales or missing files.

Select the Markdoc handler and the visible metadata #

Install and link the CLI from the project root:

sh
npm install --global @lingo.dev/cli
lingo login
lingo init --source en --targets es --files 'src/content/en/pages/*.mdoc' --yes
lingo link

Keep the generated organization and localization engine IDs in .lingo/config.json, then configure the complete source selection:

json
{
  "orgId": "org_...",
  "engineId": "eng_...",
  "sourceLocale": "en",
  "targetLocales": ["es"],
  "files": [
    {
      "pattern": "src/content/en/pages/*.mdoc",
      "format": "markdoc",
      "translateFrontmatterFields": ["title", "description"]
    },
    {
      "pattern": "src/content/en/blog/*.mdoc",
      "format": "markdoc",
      "translateFrontmatterFields": ["title", "description"]
    },
    { "pattern": "src/content/en/ui.json" }
  ]
}

.mdoc selects Markdoc automatically; the explicit format makes the intention visible. If an existing project stores Markdoc syntax in .md, set format: "markdoc" explicitly. Otherwise extension detection chooses ordinary Markdown. That difference matters for custom tags and selected component attributes.

Select visible frontmatter fields deliberately. Keep dates, authors, stable IDs, and routing metadata unchanged unless your content policy requires a specific transformation. Declare translatable component props only when they contain reader-facing text. See Markdoc for handler behavior and CLI configuration for the file option names; document API options use a different schema.

Use one UI catalog per locale. For other site-generator layouts, see Static content.

Render the source homepage through its locale route #

Give src/content/en/pages/home.mdoc a title and description in YAML frontmatter, followed by its article body. In src/content/en/ui.json, add {"home": "Home"} for the navigation label. Install @markdoc/markdoc and yaml if they are not already dependencies of the project.

This minimal src/app/[lang]/page.tsx reads the source and target homepage through the same path. It uses the current App Router's promise-based route params:

tsx
import { readFile } from "node:fs/promises";
import path from "node:path";
import React from "react";
import Markdoc from "@markdoc/markdoc";
import { parse as parseYaml } from "yaml";
import { notFound } from "next/navigation";

export const runtime = "nodejs";

export default async function Page({
  params,
}: {
  params: Promise<{ lang: string }>;
}) {
  const { lang } = await params;
  if (lang !== "en" && lang !== "es") notFound();

  const root = path.join(process.cwd(), "src/content", lang);
  let rawDocument: string;
  let rawUi: string;
  try {
    [rawDocument, rawUi] = await Promise.all([
      readFile(path.join(root, "pages/home.mdoc"), "utf8"),
      readFile(path.join(root, "ui.json"), "utf8"),
    ]);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === "ENOENT") notFound();
    throw error;
  }

  const ast = Markdoc.parse(rawDocument);
  const errors = Markdoc.validate(ast);
  if (errors.some(({ error }) => ["error", "critical"].includes(error.level))) {
    throw new Error("Invalid Markdoc document");
  }
  const metadata = parseYaml(ast.attributes.frontmatter ?? "");
  const ui = JSON.parse(rawUi);
  if (typeof metadata?.title !== "string" || typeof ui.home !== "string") {
    throw new Error("Missing homepage title or navigation label");
  }

  const tree = Markdoc.transform(ast);
  return (
    <main lang={lang}>
      <nav><a href={`/${lang}`}>{ui.home}</a></nav>
      <h1>{metadata.title}</h1>
      {Markdoc.renderers.react(tree, React)}
    </main>
  );
}

Open /en first. This example uses standard Markdoc nodes. For a site with custom tags, pass its actual configuration to both Markdoc.validate and Markdoc.transform, then supply the named React components to Markdoc.renderers.react. Pass required variables explicitly. The translation handler preserves annotations; it does not supply the site's tag schema.

Extend the same validated loader to metadata generation and other routes. For dynamic document slugs, resolve a known inventory entry before reading a path. A Node filesystem loader needs the content files included in the deployed artifact; verify their inclusion in the production build. An Edge deployment without filesystem access needs a different storage reader.

Make locale negotiation and navigation agree #

For routes without a locale, use the application's explicit preference or negotiate a supported locale from Accept-Language. Parse quality weights and regional tags, then redirect to the corresponding [lang] route while preserving the rest of the path.

Do not redirect routes that already carry a supported locale, API requests, Next.js internal assets, or static files. A broad matcher can create loops or redirect image requests into document routes. Apply the exclusions supported by your installed Next.js routing interception API. Earlier projects use middleware; newer versions may use the renamed proxy convention. Keep the behavior and tests aligned with the installed version rather than copying an old filename as a universal recipe.

Build internal and alternate-language links from known route mappings. Confirm that each target exists before offering it in a language switcher. Check heading fragments too, because translated headings can produce different generated IDs.

Generate only routes whose documents are available #

For static generation, enumerate supported locale-and-slug pairs from the actual content inventory. Include them in the project's generateStaticParams flow and inspect the generated routes. For dynamic loading, apply the same inventory check at request time and handle missing files deliberately. Do not generate every target route from the locale list while assuming its translation exists.

Translate missing target files with lingo push --backfill-missing --wait. After completion, confirm that src/content/es/pages/home.mdoc and src/content/es/ui.json exist, then open /es through the same loader. Inspect the translated title, description, body, links, code fences, and custom-tag structure. Code examples and behavioral attributes should retain their source meaning and values.

When local target corrections need divergence protection, submit without --wait and inspect lingo pull --dry-run before retrieval; direct waiting writeback lacks that gate. Follow Preserve reviewed translations.

Verify a page before making translation recurring #

Open a target-locale route directly, then navigate to it through the site. Confirm that the heading, UI chrome, metadata, and language switch all use the intended locale. Check a custom component and a code example, and follow an internal link and a heading fragment. Run the project's existing Next.js build and Markdoc validation against the translated files.

Keep sources, accepted targets, configuration, and the CLI lockfile together. Later source changes use the normal lingo push --wait workflow. Once the page works, choose managed GitHub translation or a runner recipe with reviewable writeback. Keep the content loader's validation and Next.js build in that cycle; lingo check does not establish document completeness or valid custom-tag rendering.