Skip to content

Commit 9a5a032

Browse files
authored
fix(docs): apply the requested locale to the 404 page in the browser (#213)
app/not-found.tsx sits above the [lang] segment and hardcoded en, so a reader browsing in their own language got English 404 copy. A synchronous script reads the locale from the first path segment and sets documentElement.lang, the title and the copy together. Reading a middleware-set header through headers() was built and rejected by measurement: app/not-found.tsx is the root not-found boundary, so a dynamic API in it takes the whole app from 577 prerendered documents to 1. With no prerendered param set left, dynamicParams = false stops rejecting -- /foo.bar/privacy back to 200, /foo.bar/docs back to 500, docs 404s back to the 594-byte empty shell. That undoes #180, #182, #192 and #209 while passing every gate. The route stays prerendered. The served document remains byte-identical across all eleven unmatched URLs (479133a8...), 577 prerendered files, and the seven healthy control pages are byte-identical once content-hashed asset URLs are masked. suppressHydrationWarning is required, not decorative: without it React patches the English copy back in. Zero hydration complaints measured under next dev. With scripting disabled the page is byte-for-byte what main serves today. lang is en between parse and script execution; the page carries noindex and a 404 body is not indexed, so no consumer of parse-time lang exists here. Closes #191
1 parent d0ee357 commit 9a5a032

1 file changed

Lines changed: 105 additions & 10 deletions

File tree

‎apps/docs/app/not-found.tsx‎

Lines changed: 105 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { i18n } from '@/lib/i18n';
2+
13
/**
24
* 404 shell for routes that are not under the `[lang]` segment.
35
*
@@ -11,20 +13,104 @@
1113
*
1214
* - a path that matches no route (`/no-such-page`), which Next serves from the
1315
* root `_not-found` entry;
14-
* - `notFound()` thrown by a page below `[lang]` (`/docs/no-such-page`), which
15-
* unwinds to the nearest not-found boundary. That boundary is this one, and it
16-
* sits above the locale layout, so that layout's shell is replaced rather than
17-
* wrapped. There is no nesting risk and exactly one root element either way.
16+
* - a first segment that is not an enumerated locale (`/foo.bar/privacy`) or an
17+
* unknown docs slug (`/docs/no-such-page`), both of which `dynamicParams =
18+
* false` rejects at the routing level and routes to that same entry.
1819
*
19-
* `en` is hardcoded deliberately: this boundary is above the locale segment and
20-
* cannot read it, which is the same position the root layout was in before. That
21-
* is what `main` declared here, and matching it keeps the 404 unchanged by the
22-
* locale work rather than quietly redesigned by it. The markup below reproduces
23-
* the Next.js built-in 404 that `main` rendered through the old root layout.
20+
* This boundary is above the locale segment and cannot read it. The server
21+
* markup below therefore declares `en` — what `main` has always declared here —
22+
* and the locale is applied in the browser instead, by the script at the end of
23+
* the body.
24+
*
25+
* ## Why the locale is applied client-side and not server-side
26+
*
27+
* The obvious fix is to have `middleware.ts` put the negotiated locale in a
28+
* request header and read it here through `headers()`. It was built and
29+
* measured, and it is not viable: this file is the root not-found boundary, so
30+
* it sits in *every* route's tree, and a dynamic API in it opts the whole app
31+
* out of static generation. Measured on this tree, with `middleware.ts` left
32+
* byte-identical to `main` so the reading is attributable to this file alone:
33+
*
34+
* - prerendered HTML documents fall from **577 to 1**;
35+
* - `/`, `/[lang]`, `/[lang]/docs/[[...slug]]`, `/[lang]/privacy` and
36+
* `/[lang]/terms` all go from prerendered to server-rendered on demand;
37+
* - `dynamicParams = false` stops rejecting anything, because there is no
38+
* prerendered param set left to reject against. `/foo.bar/privacy` answers
39+
* **200** again and `/foo.bar/docs` answers **500** again, undoing #209 and
40+
* #180;
41+
* - `/docs/no-such-page` and `/zh-Hans/docs/no-such-page` come back as the
42+
* 594-byte empty error shell, undoing #182 and #192.
43+
*
44+
* The comment in `app/layout.tsx` predicted the first of those. The rest was
45+
* only visible by building it.
46+
*
47+
* `app/[lang]/not-found.tsx` is not an alternative either — #182 measured it as
48+
* a no-op with byte-identical output and an identical route table.
49+
*
50+
* ## What the script does, and what it deliberately does not
51+
*
52+
* `middleware.ts` already redirects a prefix-less path to the reader's
53+
* negotiated locale before anything renders, so a non-English reader who
54+
* follows a stale link is at `/zh-Hans/...` by the time this page is served.
55+
* The locale is therefore in the URL for every request that has one at all, and
56+
* reading it from `location.pathname` needs no header and no dynamic render.
57+
*
58+
* The page stays `○` prerendered: one document, served byte-identical for every
59+
* unmatched URL, which is the property #209 measured and pinned.
60+
*
61+
* The cost, stated plainly: the document declares `en` at parse time and is
62+
* corrected once the script runs. That is invisible to indexing (a 404 body is
63+
* not indexed, and a crawler is told 404 either way) and it never produces an
64+
* inconsistent document — `lang` and the copy are set together in one
65+
* synchronous block, so the page is either English-declaring-English or
66+
* Chinese-declaring-Chinese, never one over the other. With scripting off it
67+
* stays exactly what `main` serves today.
68+
*
69+
* The markup reproduces the Next.js built-in 404. It is not a designed error
70+
* page and should not grow navigation or search.
71+
*/
72+
73+
/**
74+
* 404 copy per locale. English is the source; a locale missing from this table
75+
* keeps English, which is the same fallback Fumadocs applies to an untranslated
76+
* page. `content/docs/` translations are derived artifacts refreshed by a
77+
* separate pass (AGENTS.md, "Translation workflow"); this table is UI copy in
78+
* app code, the shape `app/[lang]/privacy/page.tsx` already uses.
79+
*/
80+
const COPY: Record<string, string> = {
81+
en: 'This page could not be found.',
82+
'zh-Hans': '找不到此页面。',
83+
ja: 'このページは見つかりませんでした。',
84+
de: 'Diese Seite konnte nicht gefunden werden.',
85+
es: 'No se ha podido encontrar esta página.',
86+
fr: 'Cette page est introuvable.',
87+
ko: '이 페이지를 찾을 수 없습니다.',
88+
};
89+
90+
/**
91+
* Inlined verbatim into a `script` element, so it must stay free of anything
92+
* that could close that element early. Every value it embeds is a compile-time
93+
* constant in this file and in `lib/i18n.ts`; none carries markup.
94+
*
95+
* `i18n.languages` is read rather than `Object.keys(COPY)` on purpose: the
96+
* locale list is the authority for what may appear as a first segment, and a
97+
* locale that is in the list but not yet in `COPY` must fall through to English
98+
* rather than be treated as an unknown segment.
2499
*/
100+
const APPLY_LOCALE = `(function(){try{
101+
var copy=${JSON.stringify(COPY)};
102+
var langs=${JSON.stringify(i18n.languages)};
103+
var seg=location.pathname.split('/')[1];
104+
if(langs.indexOf(seg)===-1||!copy[seg])return;
105+
document.documentElement.lang=seg;
106+
document.title='404: '+copy[seg];
107+
var el=document.getElementById('nf-message');
108+
if(el)el.textContent=copy[seg];
109+
}catch(e){}})();`;
110+
25111
export default function NotFound() {
26112
return (
27-
<html lang="en" suppressHydrationWarning>
113+
<html lang={i18n.defaultLanguage} suppressHydrationWarning>
28114
<body className="flex flex-col min-h-screen">
29115
<title>404: This page could not be found.</title>
30116
<div
@@ -61,7 +147,15 @@ export default function NotFound() {
61147
404
62148
</h1>
63149
<div style={{ display: 'inline-block' }}>
150+
{/*
151+
`suppressHydrationWarning` because the script below rewrites this
152+
text before React hydrates. Without it React treats the rewritten
153+
text as a mismatch and patches English back in — measured in a
154+
real browser, which is the only place that difference is visible.
155+
*/}
64156
<h2
157+
id="nf-message"
158+
suppressHydrationWarning
65159
style={{
66160
fontSize: 14,
67161
fontWeight: 400,
@@ -74,6 +168,7 @@ export default function NotFound() {
74168
</div>
75169
</div>
76170
</div>
171+
<script dangerouslySetInnerHTML={{ __html: APPLY_LOCALE }} />
77172
</body>
78173
</html>
79174
);

0 commit comments

Comments
 (0)