By using independent document isolation, full-article hash caching, and MDX placeholder protection, the system automatically translates body text and interface terms within DeepL’s quota.
Why this matters
For a personal tech blog focused on systems engineering, Agent toolchains, and developer workflows, it’s a shame for the content to remain confined to a Chinese-language context—many in-depth troubleshooting cases and architectural insights could also serve as valuable references for developers and open-source communities worldwide. However, when faced with “internationalization (i18n),” the vast majority of personal sites often find themselves in a dilemma:
- Purely manual bilingual maintenance: Writing a Chinese blog post and then manually creating an English version. As the number of articles increases and daily revisions continue, the two sets of MDX files will quickly become significantly out of sync, eventually turning into a burden that is abandoned.
- Pure front-end machine translation plugins: Using client-side JavaScript plugins like Google Translate. Not only does this cause noticeable layout shifts (CLS) on the page, but more critically, search engine crawlers cannot index the statically translated content, making it impossible to generate separate English URLs,
hreflangtags, and a sitemap—rendering it completely worthless for technical SEO and generative AI search (GEO).
This article documents how this site integrated the DeepL API to build a bilingual system: UI terms and body text are translated separately; code and tags are first replaced with placeholders; the English content is stored in a dedicated document type within Contentlayer; SHA-256 is used to verify whether the entire original article has been modified; and GitHub Actions then create a pull request. Translation is billed based on the actual number of characters returned by DeepL.
Core Architecture Design
Before writing the translation script, the primary question was: In what format should the translated English body text exist within the system?
1. Architectural Isolation: Protecting the Knowledge Graph and Native Routing
This site uses Contentlayer to build a static content model. Articles are not only standalone pages but also deeply involved in the calculation of the site-wide knowledge graph, topic classification (Territories), and bidirectional reference links for project case studies (Case Studies).
If we simply treat English articles as ordinary Blog documents (for example, by placing files under data/blog/en/), this would lead to critical side effects:
- The number of
allBlogsentries would double, as would the number of nodes and edges in the graph, disrupting the original graph topology; - Confusion in the statistics regarding the number of tagged articles and the total number of domains;
- Contamination or conflicts with the existing URL routing of the original Chinese articles.
Therefore, we have established a separate document type, BlogTranslation, within contentlayer.config.ts:
// contentlayer.config.ts
export const BlogTranslation = defineDocumentType(() => ({
name: 'BlogTranslation',
filePathPattern: 'blog-i18n/**/*.mdx',
contentType: 'mdx',
fields: {
title: { type: 'string', required: true },
date: { type: 'date', required: true },
tags: { type: 'list', of: { type: 'string' }, default: [] },
summary: { type: 'string' },
tldr: { type: 'string' },
sourceHash: { type: 'string' },
translatedAt: { type: 'string' },
},
computedFields: {
slug: {
type: 'string',
resolve: (doc) => doc._raw.flattenedPath.split('/').slice(2).join('/'),
},
locale: {
type: 'string',
resolve: (doc) => doc._raw.flattenedPath.split('/')[1] || 'en',
},
},
}));
English translations are uniformly stored in data/blog-i18n/en/*.mdx, generating a separate allBlogTranslations collection:
allBlogsPreserves the Original Content: Includes only the original Chinese manuscripts; the knowledge graph, tag association model, and routing do not account for the English translations;- On-demand rendering: When accessing
/en/blog/[slug], the system prioritizes retrieving English titles, abstracts, and MDX body text fromallBlogTranslations; if a translation is temporarily unavailable, it seamlessly falls back to displaying the Chinese version and shows a friendly prompt.
2. Automated Pipeline: Separate Processing for UI Entries and Article Body Text
Translation requirements fall into two categories, each with completely different data characteristics and translation strategies:
| Dimension | UI Interface Terms (messages/*.json) | Blog Article Body (data/blog/*.mdx) |
|---|---|---|
| Data Format | Structured, nested JSON key-value pairs | Rich-text MDX containing Frontmatter and JSX |
| Variable Protection | ICU syntax interpolation (e.g., {count, plural, ...}) | Inline code, code blocks, LaTeX mathematical formulas, HTML containers |
| Incremental Strategy | Key Diff (translates only keys missing from English JSON) | SHA-256 content hash comparison (zero calls if unmodified) |
| Execution Script | scripts/translate-messages.mjs | scripts/translate-blog.mjs |
UI Entry Protection
UI entries often contain next-intl parameter placeholders. Before calling DeepL, the script uses these placeholders to replace {param} with special markers that cannot be translated; these are precisely restored after translation to prevent variable names from being mistakenly altered by the translation engine.
SHA-256 Incremental Caching for Body Text
In the Frontmatter at data/blog-i18n/en/*.mdx, the entire original Chinese manuscript is recorded as sourceHash. Each time the pipeline scans:
const currentHash = crypto.createHash('sha256').update(rawContent).digest('hex');
if (existingTranslation?.sourceHash === currentHash) {
// 整篇原文未改,跳过
continue;
}
The hash covers the entire MDX file, including the Frontmatter. Changing a title or a paragraph of the body text triggers a full re-translation of the entire document—not just the modified sections. Articles with a matching hash will not call DeepL again.
Troubleshooting Log: Resolving the Technical Challenge of Machine Translation Corrupting MDX Syntax
When feeding long Markdown/MDX files into a machine translation API, the most common issue isn’t semantic incoherence, but rather format corruption causing the compilation to fail outright. When we first translated all existing articles into English, we encountered two main challenges:
Challenge 1: Indentation Issues in YAML Frontmatter
In many articles, summary or tldr are used in YAML to collapse multi-line text (>-). Early scripts that used simple regular expressions for single-line replacements often caused the translated English multi-line text to lose indentation or contain extra indentation, resulting in syntax errors from the YAML parser:
YAMLException: All mapping items must start at the same column
Solution: Completely phase out regular expression-based text replacement and strictly use gray-matter for Frontmatter parsing and serialization:
const parsed = matter(rawContent);
// 仅翻译必要字段
const translatedTitle = await translateText(parsed.data.title);
const translatedSummary = await translateText(parsed.data.summary);
const translatedTldr = await translateText(parsed.data.tldr);
// 使用 gray-matter 严谨回写
const output = matter.stringify(translatedBody, {
...parsed.data,
title: translatedTitle,
summary: translatedSummary,
tldr: translatedTldr,
sourceHash: currentHash,
translatedAt: new Date().toISOString(),
});
This fundamentally eliminates indentation and YAML special character escaping issues.
Challenge 2: MDX/JSX Container Tags Being Split and Fragmented
MDX compilers (acorn / remark) are very strict about the boundaries between paragraphs and JSX blocks. In articles containing custom components or HTML tags, DeepL frequently exhibits two types of destructive behavior:
- Nested closing tags are merged or lost: For example, the original
</div></div></div>is interpreted by machine translation as duplicate invalid markup and reduced to two</div>; - Tags and content are split across lines: For example, the original table cell
<th className="px-4 py-2">Scenario</th>
It may be translated as:
<th className="px-4 py-2">场景</th>
The opening tag is on a new line and the closing tag is appended to the end; acorn will directly report an error: Expected closing tag before end of paragraph.
Solution: A two-tier isolation and compacting cleanup strategy.
Insert placeholders before translation, then submit the entire document: Replace code blocks, inline code, formulas, URLs, and JSX tags with placeholders. Paragraphs without Chinese text should also be converted to placeholders, but they must remain in the same request as the surrounding body text to prevent misinterpretation of pronouns like “the other party” when split across requests. If placeholders are missing or insufficient, do not submit the text. DeepL sometimes drops strings of placeholders in long texts; in such cases, retry the entire document by paragraph.
separateBlockTagsis only responsible for separating tags on their own lines into separate paragraphs.Post-Translation Compaction and Cleaning: For structures like
<tag>\n text</tag>that are broken across lines, regular expressions automatically collapse them into a compact, single-line format and remove non-compliant stray blank lines within the container:// 清理 JSX 标签内部的多余换行 restored = restored.replace( /<([a-z][a-z0-9]*)\s*([^>]*)>\s*\n\s*([^<\n]+)\s*<\/\1>/gi, '<$1 $2>$3</$1>', );CI Pre-Interception Safeguards: In the GitHub Actions pipeline, add a
npx contentlayer2 buildvalidation step before submitting a PR. Even if the translation script outputs syntactically flawed MDX due to an isolated issue, it will fail and be intercepted on the spot during the CI runner phase, ensuring that uncompilable code is never committed to the repository.
In-Depth Localization of the Entire Site Interface
When implementing multilingual support, many projects tend to stop at “allowing language switching on article detail pages.” However, from the perspective of the actual reader experience, if the article list, tags, and archive timeline on the /en homepage remain in Chinese, the experience will feel very disjointed.
To address this, we’ve built a unified localization data layer:
1. Unified Extraction Tool getLocalizedPosts(locale) Encapsulate unified functions in lib/postTranslations.ts:
export function getLocalizedPosts(locale?: string): CoreContent<Blog>[] {
const sorted = allCoreContent(sortPosts(allBlogs));
if (!locale || locale === 'zh') return sorted;
const translationMap = new Map(
allBlogTranslations
.filter((t) => t.locale === locale)
.map((t) => [t.slug, t]),
);
return sorted.map((post) => {
const trans = translationMap.get(post.slug);
if (!trans) return post;
return {
...post,
title: trans.title || post.title,
summary: trans.summary || post.summary,
tldr: trans.tldr || post.tldr,
};
});
}
Whether in the home page writing area (WritingSection), archive pages (/blog), knowledge node pages (/knowledge/[node]), or tag pages, simply passing in the current page’s language environment will retrieve the title and summary in the corresponding language.
2. Automatic Internationalization of Tags and Typography Styles
In the list display component TraceList, integrate useTranslations('tags') and map Chinese tags to English during rendering:
const tTags = useTranslations('tags');
const formatTag = (tag: string) => {
const tagSlug = slug(tag);
if (tTags.has(tagSlug)) return tTags(tagSlug);
if (!tag.includes('.') && tTags.has(tag)) return tTags(tag);
return tag;
};
In the English interface, combined with the site’s typography token type-meta (which includes text-transform: uppercase), tags automatically display with a refined typography style:
运维→OPERATIONS独立开发→INDIE DEVELOPMENT打印机→PRINTER
Operating Costs and Results
This pipeline initially translated the 25 articles available at the time into English; DeepL estimated the total at approximately 182,000 characters. Each article typically took between a few seconds and over ten seconds to process. Subsequently, every time a Chinese draft was modified, the entire article was re-billed.
When a Chinese draft is pushed to main and changes are made to data/blog/ or messages/zh.json, GitHub Actions will run the translation. It can also be manually triggered within Actions. After translation, a pull request (PR) is opened; once reviewed and merged, the content is deployed to the production environment via Vercel. There are no scheduled daily tasks. If a particular article has not been written in English, this step should end in failure rather than reporting success and skipping the process.
Summary and Engineering Insights
The most profound insight gained from building this automated multilingual blog pipeline is: The internationalization of a content system is, at its core, about data flow design and error-tolerant syntax management.
- Single Source of Truth: Always treat the original Chinese manuscript as the primary data source, with translation files serving as read-only, generated copies. Avoid making content modifications on both sides simultaneously, as this will inevitably lead to desynchronization.
- Separate Code and Sentences: The translation engine processes sentences but does not understand the Markdown syntax tree. Before submission, replace code, formulas, and tags with placeholders. If a placeholder is not returned unchanged, it is not written into the translated text.
- Validation Remains Within CI: Script tests and Contentlayer builds are responsible for filtering out translations that fail compilation. If a single translation fails, the task itself must also fail, preventing bad hashes from remaining in
mainand causing character limits to be reapplied with every push.