Skip to content

Commit 4ab8888

Browse files
committed
Leave the base path to next/link instead of reading it in the browser
The previous fix was wrong in a way its tests could not see. Markdown is a client component, so markdownLinks ships in the browser bundle, and NEXT_BASE_PATH is not NEXT_PUBLIC_-prefixed: Next strips it from that bundle. Under a configured base path the static render - which runs in node, where the variable exists - emitted /preview/docs/..., and the same code after hydration emitted /docs/..., so the href changed under the reader and React had a mismatch to reconcile. Nothing in the exported HTML shows this, because the export is produced by the server-side render that reads the variable correctly. The tests passed for the same reason: vitest runs in node. The resolver is pure again and returns a base-path-relative route. The anchor renderer now uses next/link for a rewritten href, which is by definition an internal document route, and next/link applies the basePath from next.config on both the server and the client. Hrefs the resolver leaves alone still render as plain anchors, so external links, fragments and hand-written absolute paths behave exactly as before. Coverage follows the same reasoning. The base-path tests now assert the route is unchanged whether or not NEXT_BASE_PATH is set, and a source guard asserts neither client-reachable module mentions NEXT_BASE_PATH, sitePath or withBasePath. A build-level check would not have caught this and would not catch a regression: the markup on disk is correct in both the broken and the fixed version. Proving the browser behaviour would need hydration testing, which the project has no harness for today - jsdom and testing-library are not dependencies - so the guard is placed where the mistake is made instead. Note Navbar has the same latent defect: it calls withBasePath at module scope in a client component, for the blogs anchor and the logo image. Left alone here, since it is a different surface and this branch should not grow to cover it.
1 parent 91594e0 commit 4ab8888

3 files changed

Lines changed: 85 additions & 15 deletions

File tree

‎app/components/Markdown.tsx‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import ReactMarkdown from "react-markdown";
44
import remarkGfm from "remark-gfm";
5+
import Link from "next/link";
56
import { useMemo } from 'react';
67
import type { ReactElement } from 'react';
78
import Code from './Code';
@@ -255,10 +256,26 @@ function getMarkdownComponents(sourcePath: string) {
255256
a: ({ children, href, ...props }: any) => {
256257
const resolvedHref = resolveMarkdownLink(href, sourcePath);
257258
const isExternal = /^https?:\/\//i.test(resolvedHref ?? '');
259+
const linkClassName = 'text-blue-400 hover:text-blue-300 transition-colors';
260+
261+
// A rewritten href is a resolved document route, so it is known to be an
262+
// internal page and is rendered with next/link. That applies the basePath
263+
// from next.config identically on the server and in the browser -
264+
// NEXT_BASE_PATH is not readable from the client bundle, so neither this
265+
// component nor the resolver may prefix the path itself. Any other href
266+
// is left exactly as the author wrote it.
267+
if (resolvedHref && resolvedHref !== href) {
268+
return (
269+
<Link href={resolvedHref} className={linkClassName} {...props}>
270+
{children}
271+
</Link>
272+
);
273+
}
274+
258275
return (
259276
<a
260277
href={resolvedHref}
261-
className="text-blue-400 hover:text-blue-300 transition-colors"
278+
className={linkClassName}
262279
{...(isExternal ? { target: '_blank', rel: 'noopener noreferrer' } : {})}
263280
{...props}
264281
>

‎app/lib/markdownLinks.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1-
import { withBasePath } from '../services/sitePath';
2-
1+
// Deliberately free of any base-path handling. This module is reachable from a
2+
// client component, and NEXT_BASE_PATH is not NEXT_PUBLIC_-prefixed, so its
3+
// value is stripped from the browser bundle: reading it here would produce a
4+
// prefixed href during the static render and an unprefixed one after
5+
// hydration. The route returned below is base-path-relative, and the caller
6+
// renders it with next/link, which applies the basePath configured in
7+
// next.config on both the server and the client.
38
const markdownOrigin = 'https://documentdb.invalid';
49

510
const docsRoot = '/docs/';
@@ -62,7 +67,5 @@ export function resolveMarkdownLink(
6267

6368
const publishedPathname = applySectionMapping(target.pathname);
6469

65-
// Rendered as a plain anchor rather than next/link, so the base path is not
66-
// applied for us - a subpath deployment needs it added here.
67-
return `${withBasePath(publishedPathname)}${target.search}${target.hash}`;
70+
return `${publishedPathname}${target.search}${target.hash}`;
6871
}

‎tests/markdownLinks.test.ts‎

Lines changed: 59 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -90,45 +90,49 @@ describe('resolveMarkdownLink', () => {
9090
});
9191
});
9292

93-
describe('resolveMarkdownLink with a configured base path', () => {
93+
// The resolver runs inside a client component. NEXT_BASE_PATH is not
94+
// NEXT_PUBLIC_-prefixed, so its value is stripped from the browser bundle:
95+
// anything that reads it here yields a prefixed href during the static render
96+
// and an unprefixed one after hydration, which is invisible in the exported
97+
// HTML and only shows up in a browser. The route must therefore stay
98+
// base-path-relative, and next/link applies the prefix on both sides.
99+
describe('resolveMarkdownLink under a configured base path', () => {
94100
afterEach(() => {
95101
vi.unstubAllEnvs();
96102
vi.resetModules();
97103
});
98104

99-
// sitePath reads NEXT_BASE_PATH once at module scope, so the module has to be
100-
// re-imported after the environment is stubbed.
101105
async function importWithBasePath(basePath: string) {
102106
vi.resetModules();
103107
vi.stubEnv('NEXT_BASE_PATH', basePath);
104108
return (await import('../app/lib/markdownLinks')).resolveMarkdownLink;
105109
}
106110

107-
it('prefixes the resolved route, since the anchor is not a next/link', async () => {
111+
it('returns an unprefixed route, leaving the base path to next/link', async () => {
108112
const resolve = await importWithBasePath('/preview');
109113

110114
expect(resolve('functions.md', '/docs/postgres-api/index.md')).toBe(
111-
'/preview/docs/postgres-api/functions/',
115+
'/docs/postgres-api/functions/',
112116
);
113117
});
114118

115-
it('prefixes a mapped cross-section route as well', async () => {
119+
it('leaves a mapped cross-section route unprefixed as well', async () => {
116120
const resolve = await importWithBasePath('/preview');
117121

118122
expect(
119123
resolve(
120124
'../api-reference/operators/aggregation/%24limit.md',
121125
'/docs/getting-started/index.md',
122126
),
123-
).toBe('/preview/docs/reference/operators/aggregation/%24limit/');
127+
).toBe('/docs/reference/operators/aggregation/%24limit/');
124128
});
125129

126-
it('keeps the query and fragment after the prefixed path', async () => {
130+
it('keeps the query and fragment intact', async () => {
127131
const resolve = await importWithBasePath('preview');
128132

129133
expect(
130134
resolve('python-setup.md?view=full#connect', '/docs/getting-started/index.md'),
131-
).toBe('/preview/docs/getting-started/python-setup/?view=full#connect');
135+
).toBe('/docs/getting-started/python-setup/?view=full#connect');
132136
});
133137

134138
it('leaves links it does not rewrite untouched', async () => {
@@ -139,4 +143,50 @@ describe('resolveMarkdownLink with a configured base path', () => {
139143
resolve('https://example.com/readme.md', '/docs/getting-started/index.md'),
140144
).toBe('https://example.com/readme.md');
141145
});
146+
147+
it('produces the same route whether or not a base path is configured', async () => {
148+
const withPreview = await importWithBasePath('/preview');
149+
const resolvedWithPreview = withPreview(
150+
'functions.md',
151+
'/docs/postgres-api/index.md',
152+
);
153+
154+
vi.unstubAllEnvs();
155+
vi.resetModules();
156+
const { resolveMarkdownLink: withoutPreview } = await import(
157+
'../app/lib/markdownLinks'
158+
);
159+
160+
expect(resolvedWithPreview).toBe(
161+
withoutPreview('functions.md', '/docs/postgres-api/index.md'),
162+
);
163+
});
164+
});
165+
166+
// A build-level assertion on the exported HTML cannot catch this: the export is
167+
// rendered server-side, where the variable is readable, so the emitted markup
168+
// looks correct and only the hydrated page is wrong. Guard it at the source
169+
// instead, which is where the mistake is actually made.
170+
describe('client-reachable modules and the private base path', () => {
171+
const clientReachableSources = [
172+
'app/lib/markdownLinks.ts',
173+
'app/components/Markdown.tsx',
174+
];
175+
176+
it.each(clientReachableSources)(
177+
'%s does not read NEXT_BASE_PATH or import sitePath',
178+
async (relativePath) => {
179+
const { readFile } = await import('node:fs/promises');
180+
const { fileURLToPath } = await import('node:url');
181+
const source = await readFile(
182+
fileURLToPath(new URL(`../${relativePath}`, import.meta.url)),
183+
'utf8',
184+
);
185+
const code = source.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\//g, '');
186+
187+
expect(code).not.toContain('NEXT_BASE_PATH');
188+
expect(code).not.toContain('sitePath');
189+
expect(code).not.toContain('withBasePath');
190+
},
191+
);
142192
});

0 commit comments

Comments
 (0)