vi

blog

Bilingual Next.js static blog: translationOf, hreflang and a build-failing gate

Each post is 2 Markdown files joined by a single translationOf line. The URL map, hreflang tags, language switch and a build-failing gate all derive from that line, with no Next i18n.

Published
Next.js 16i18nhreflangStatic export
2 file cards side by side labeled vi and en, joined by a double-headed arrow, with the translationOf line highlighted in the en card and 3 small bars below reading hreflang vi, en and x-default

A bilingual blog on a static export needs one frontmatter line in the English file to join a pair. The URL map, hreflang tags, language switch and a build-failing gate all derive from that line, so the Vietnamese file stays untouched when a translation is added. The plan for this site's English version ruled out Next's i18n, because static export does not support it: a page's language comes straight from its slug.

The English file declares translationOf, the Vietnamese file stays untouched

content/en/ repeats the tree of content/. lib/mdx-files.js flattens the blog folder the way the Vietnamese side does: content/blog/x.md becomes /x, content/en/blog/y.md becomes /en/y. A single catch-all, pages/[[...slug]].js, serves both, as described in the Markdown-driven Next.js site architecture. The language comes from the first element of the slug:

js
export const localeOfSlug = (slug) => (Array.isArray(slug) && slug[0] === 'en' ? 'en' : 'vi')

The pair is joined by one line placed right after layout: in the English file. This is the real frontmatter of the English version of the subagent post:

yaml
---
layout: BlogPost
translationOf: /toi-uu-subagent-claude-code-sdd
date: '2026-11-04'
updated: '2026-11-11'
---

That post's English slug is claude-code-subagent-cost-optimization, nothing like the Vietnamese slug, because it carries the keyword an English reader types into Google. translationOf is a URL string, not a file name, so the 2 slugs do not have to match. The only exception is project slugs, which are brand names.

2 more places read the translationOf line. scripts/generate-sitemaps.js uses it to print 3 xhtml:link tags for every URL that has a pair. The source gate finds the Vietnamese sidecar through it, so the English post has no sidecar of its own; one is needed only when a number changes form (for example "150 nghìn" becoming "150,000").

lib/translations.js builds the two-way map

Only the English file declares the pair, so the map is built by scanning content/en/**. Each pair writes 2 entries, so a lookup from either side finds the other:

js
async function buildMap() {
  if (cache) return cache
  const map = new Map()
  for (const { slug, filePath } of await getFiles('en', getMdxOptions())) {
    const { translationOf } = matter.read(filePath).data
    if (!translationOf) continue
    map.set(toUrl(slug), translationOf)
    map.set(translationOf, toUrl(slug))
  }
  cache = map
  return map
}

export async function getAlternates(slug) {
  const self = slug.length ? toUrl(slug) : '/'
  const other = (await buildMap()).get(self)
  const isEn = slug[0] === 'en'
  if (!other) return isEn ? { en: self } : { vi: self }
  return isEn ? { vi: other, en: self } : { vi: self, en: other }
}

A page without a pair gets back an object with a single key. That is the signal for the next layer to print nothing. getStaticProps calls this function and pushes locale and alternates into the page props.

hreflang prints only when both sides exist

components/Seo.jsx takes alternates and builds languageAlternates only when both vi and en are present:

jsx
const languageAlternates =
  alternates.vi && alternates.en
    ? [
        { hrefLang: 'vi', href: abs(alternates.vi) },
        { hrefLang: 'en', href: abs(alternates.en) },
        { hrefLang: 'x-default', href: abs(alternates.vi) },
      ]
    : undefined

A full pair yields 3 tags, with x-default pointing to the Vietnamese page. A missing side yields no tags at all, and og:locale:alternate follows the same condition. The list pages /page/N are forced to alternates={} in pages/[[...slug]].js: the page counts of the 2 languages can differ, so the plan chose not to emit hreflang for them.

The rule matches how the site actually is: project pages and marketing pages that exist in one language are valid with no hreflang at all. Only a lopsided tag count (1 or 2) is an error.

LanguageSwitch does not redirect by language

Readers switch language with a round button next to the theme toggle. The logic that picks the target fits in 2 lines of components/LanguageSwitch.jsx:

jsx
const target = locale === 'en' ? 'vi' : 'en'
const href = alternates?.[target] || (target === 'en' ? '/en' : '/')

With a pair it links to the other post; without one it goes to the other language's home page. The site does not redirect by browser language: the plan settled on 31 Oct 2026 that there is only the language button and the hreflang tags.

<html lang> is set in pages/_document.js from pageProps.locale. The plan says not to derive the locale from window.location or navigator.language: server and client must see the same value, or you hit hydration #418.

check-i18n fails the build when the English file is missing

scripts/check-i18n.js runs in prebuild, before the search index step. For each file under content/en/, content/en/blog/ and content/en/projects/, it checks that:

  • translationOf is present, a string starting with /, and not /en or /en/....
  • It matches a real Vietnamese file, and equals that file's exact real URL.
  • A blog post points to a blog post, a project to a project, a page to a page.
  • Each Vietnamese URL has only 1 English version.
  • date and updated match across the 2 versions, because they drive lastmod and post order.

Then comes the reverse direction, from the Vietnamese side:

js
for (const f of mdIn(path.join(C, 'blog'))) {
  const url = '/' + f.replace(/\.md$/, '')
  if (!paired.has(url)) (STRICT ? errors : warnings).push(`content/blog/${f}: chưa có bản tiếng Anh`)
}

With STRICT = true, a new blog post without an English version stops npm run build before next build runs. When every pair matches, the gate prints one summary line of the form check-i18n: <số> cặp; on errors it prints each one with the file path and exits with code 1.

The gate was not strict from the start. In batches 1 and 2 of the plan, STRICT was false and it only warned, because the 18 older posts were not translated yet. The plan flipped STRICT = true at the end of batch 3, once all 18 had a pair, and deployed on 1 Nov 2026. Turning it on earlier would have turned every build red.

What the gate cannot catch

check-i18n compares dates, not content. Change a number in the Vietnamese post and forget the English one, and the gate stays green. That rule is kept by hand: when a fact changes, fix both versions in the same commit, with the same updated.

Rename a Vietnamese slug and the English translationOf becomes a dead string; the gate reports không khớp file nào. A cover with Vietnamese text needing its own English version, og:image being a PNG, and hreflang pointing back to the right page: the gate sees none of these, because it reads source, not the built HTML. The checks on the HTML are in the post on check:seo and check:links.

Related posts

all posts →