Skip to content

perf(docs-next): highlight API samples synchronously so the server renders them highlighted - #422

Open
nickvigilante wants to merge 2 commits into
mainfrom
vigilante/api-sample-sync-highlighter-bench
Open

nickvigilante wants to merge 2 commits into
mainfrom
vigilante/api-sample-sync-highlighter-bench

Conversation

@nickvigilante

@nickvigilante nickvigilante commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Merge order

Do not merge until the timing check in QA shows no LCP, TBT or INP regression. This change moves about 111 KB gzipped of grammars and themes into the REST API operation page's chunk, so that cost has to be measured in a browser before it lands. It is independent of the other open PRs.

Summary

On the first load of a REST API operation page, the default cURL sample can show unstyled for a moment before it is highlighted. This builds the sample highlighter synchronously, so the server renders every sample (the four sample panels and the response example) already highlighted, with no suspended placeholder and no swap script.

Design

The highlighter was created through an async call that loaded its languages. Fumadocs' Highlighted component suspends on that call, so the server rendered each sample as a plain <pre> fallback and the highlighted markup arrived later in hidden templates that inline $RC scripts swapped in. In the fixture export of /reference/api/workspaces/list-workspaces/ that was five swaps, each starting with no styled spans.

The fix in packages/docs-next/src/openapi/api-page.tsx uses createHighlighterCoreSync from shiki/core with the JavaScript regex engine and static imports of the same six grammars and two themes. The highlighter handed to createDynamicCodeBlock exposes only codeToHast and has no loadLanguage, and upstream Highlighted only suspends when loadLanguage exists, so nothing suspends. A language outside the bundle falls back to plain text. createShikiFactory({ init: () => core }) stays for createOpenAPIPageBase. No casts are needed, and the async factory and the preload call are gone.

Why synchronous: it is about 30 lines, keeps ApiPage and SampleTabs as they are, and makes the server HTML correct without depending on inline scripts, which matters with JavaScript off and for crawlers. The alternative is to highlight the samples in a server component and pass the result to the client ApiPage. That would avoid shipping Shiki for the samples at all, but it means restructuring index.tsx and SampleTabs and splitting the sample tabs across the server and client boundary. Not worth that for now; it stays open if the chunk cost turns out to matter.

The trade-off is bundle shape. The grammars (TypeScript is the largest) are already fetched for these pages today, but lazily after hydration; now they are in the operation page's preloaded chunk and load before it renders. Only operation pages are affected, and first-load JS is unchanged.

QA

Compare production (or a build of main) against this preview. Timing needs a browser, so these are browser-only steps.

  1. Chrome, in an incognito window, open DevTools. In the Network tab tick Disable cache and set throttling to Slow 4G. In the Performance tab set CPU to 4x slowdown.
  2. Open the Performance tab and click "Start profiling and reload page". Do this on the production page, three runs, then on the preview page, three runs. Note LCP, Total Blocking Time (from the timings and the Lighthouse panel if you prefer) and CLS for each run, and compare the medians. CLS must stay 0.
  3. To compare chunk size, reload each page with the Network tab open, filter by JS, and compare the largest operation-page chunk. Expect about 107 KB gzipped on production and about 183 KB with this change.
  4. Click between the cURL, JavaScript, Python and Go tabs on the preview and confirm each one is highlighted at once and nothing shifts. Interaction delay (INP) should not feel worse than production.
  5. Firefox: repeat steps 1 and 2 with the Network tab set to Disable cache and a Regular 3G or "GPRS" throttle, and compare with the Performance panel recording. I could not verify any Firefox step, and Firefox has no 4x CPU throttle.
  6. With JavaScript disabled (Chrome: DevTools, Command menu, "Disable JavaScript", then reload; Firefox: about:config, set javascript.enabled to false, then reload), open each page. Production shows plain uncoloured code in the samples; this branch shows highlighted code.

Pages to compare

Note the preview needs a Vercel login. The docs preview status link on this PR is authoritative; the preview URL is that link plus the path below.

What to check Production Preview
cURL sample highlighted on first load; chunk size; timing https://coder.com/docs/reference/api/workspaces/list-workspaces/ Use the docs preview status link on this PR, then open /reference/api/workspaces/list-workspaces/
Same page with JavaScript disabled https://coder.com/docs/reference/api/workspaces/list-workspaces/ Use the docs preview status link on this PR, then open /reference/api/workspaces/list-workspaces/

Testing

Two tests in packages/docs-next/src/openapi/api-page-samples.test.tsx pin this: the first synchronous render of the samples has styled .line span[style] in the shown cURL panel, and renderToString output parsed with DOMParser has no pending Suspense marker or B: template and a highlighted shown panel. Both fail on the current main code and pass with this change (they run first in the file because the highlighter is module-level and would otherwise already be warm). The existing tab-switching and persist tests still pass.

Ran: pnpm --filter @coder/docs-next test (493 of 493 pass), tsc --noEmit for @coder/docs-next (clean), oxfmt and oxlint on the touched files (clean), the fixture docs site build, and pnpm --filter @coder/docs-site first-load:check (passes: 68 pages, no forbidden libraries). The axe pass could not run here because headless Chromium is missing system libraries, so CI's a11y job is the check. No new UI is added.

Benchmark from DOCS-1916, build output and Node timings only, on the fixture page /reference/api/workspaces/list-workspaces/. Pending markers, templates and $RC swap scripts go from 5 each to 0, and the five code blocks are highlighted inline. Page HTML is 8.2% smaller raw (130,428 to 119,681 bytes) and 5.2% smaller gzipped. Total shiki bytes barely change across the export (+2.3 KB gzipped); about 108 KB gzipped of grammars and themes move from lazy chunks into the operation page's preloaded chunk, which grows from about 152 KB to 263 KB gzipped (470 KB to 1.18 MB raw). Highlighter creation and per-sample highlight times in Node are indistinguishable (cold runs about 45, 85, 20, 30 and 1 ms; warm runs under 1 ms), and build time is the same (about 67 s). FCP, LCP, CLS, TBT, INP and hydration time were not measured. With JavaScript on, the highlighted markup was already in the old page bytes inside hidden templates, so the visible gain may be robustness (no-JS, crawlers, no reliance on inline scripts) rather than a faster paint.

Local audit: Lighthouse, Unlighthouse and SiteOne

I built the fixture site from this branch's parent (async) and from this branch (sync), served both exports from localhost, and audited each. The browser steps in QA are still the check that matters for real-world timing, since these runs used software rendering, an uncompressed static server and a small corpus (8 API pages).

Lighthouse, 3 runs per page on 4 operation pages with the variants alternated, medians:

Mobile async Mobile sync Desktop async Desktop sync
Performance score 86 86 99 99
LCP, per-page medians 2.25 to 4.4 s 2.25 to 4.4 s about 805 ms about 804 ms
Total blocking time about 316 ms about 314 ms 30 ms 0 ms
CLS 0 0 0.002 to 0.003 0
Speed Index 4421 ms 4713 ms 991 ms 1082 ms
Accessibility, best practices, SEO 100, 96, 90 100, 96, 90 100, 96, 90 100, 96, 90

Unlighthouse over 23 routes (coder.com's settings: desktop, no throttling, one sample each) averaged 57.9 for async and 56.6 for sync. The eight REST API routes scored the same on both builds except the API landing page, which has no code samples and scored 57 against 43, so I read that as noise. Accessibility, best practices and SEO were identical.

SiteOne's performance category scored 10 of 10 on both. The crawled total rose from 4.05 MB to 4.72 MB uncompressed, with JavaScript going from 18 files to 19, which is the chunk move described under Design. HTML sizes and the 404 list were the same.

So load metrics are indistinguishable here, sync is marginally better on blocking time and layout shift on desktop, Speed Index reads slightly worse for sync but within the noise of three runs, and the one visible cost is the larger preloaded chunk. INP was not measured, and the real corpus has larger operation pages that this fixture does not reproduce.

Upstream

No. This is our own highlighter setup. The separate cause of the tab-switch flash, a new highlighter for every mount of the plain DynamicCodeBlock, is a Fumadocs bug whose report is drafted and not filed.

https://linear.app/codercom/issue/DOCS-1916


🤖 Built with AI assistance.

…nders them highlighted

The sample highlighter loaded its grammars through an async call, so fumadocs' code block suspended and the server emitted a plain placeholder for each sample, with the highlighted markup arriving later in hidden templates swapped in by inline scripts. Build the highlighter with createHighlighterCoreSync and static grammar and theme imports, and expose only codeToHast so nothing suspends. A language outside the bundle renders as plain text.

Assisted-by: AI
@vercel

vercel Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
coder-docs Skipped Skipped Dec 4, 2026 8:42pm UTC

Request Review

@linear-code

linear-code Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
DOCS-1916 Highlight the first REST API code sample on the server, with no flash on first load

On the first load of a REST API operation page, the default cURL sample shows unstyled for a moment before it is highlighted.

This is separate from DOCS-1907, which fixed the flash when switching tabs. The tab fix (#413) is merged and works.

Cause. The sample highlighter loads its languages through an async call. Fumadocs' Highlighted component suspends on that call, so the server renders each sample as a plain placeholder. The highlighted markup arrives later in hidden blocks and an inline script swaps it in.

In the fixture export of /reference/api/workspaces/list-workspaces/, there are five such swaps: four sample panels and the response example. Each starts with no styled spans.

I could not confirm how long the flash is in a browser. Whether the browser paints the plain version first depends on chunking, CSS and CPU. Hydration may add a second flash. Both are unverified.

Proposed fix. Build the highlighter synchronously with createHighlighterCoreSync from shiki/core. Import the six grammars and two themes statically, and use the JavaScript regex engine. Expose only codeToHast, with no loadLanguage. Fumadocs then renders the highlighted HTML inline, with no placeholder and no swap. The change is in packages/docs-next/src/openapi/api-page.tsx, about 30 lines.

Trade-off. The operation-page chunk gets larger, because the grammars (TypeScript is the largest) are bundled statically. They are already fetched for these pages today. The cost is that they now load before the page renders.

Decision. Nick prefers the synchronous approach if page timing is acceptable. A benchmark of sync against async (bundle size, first-load check, highlighter cost, build time) is in progress. Paint timing needs a browser, so the issue stays open until someone measures FCP, LCP and CLS on a preview.

Done when.

  • The first visible sample is highlighted in the server HTML, with no placeholder or swap script.
  • The test asserts it: the first synchronous render has styled spans, and the server output has no placeholder.
  • first-load:check passes, and the chunk size change is recorded in the PR.
  • Cumulative layout shift stays at 0.
  • The response example block is covered too, since it uses the same highlighter.

Alternative. Highlight the samples in a server component and pass the result to the client ApiPage. This avoids shipping Shiki for the samples, but it means restructuring index.tsx and SampleTabs.

Upstream. The tab-switch cause (a new highlighter for every mount of the plain DynamicCodeBlock) is a separate Fumadocs bug. A report is drafted and not filed. Filing needs Nick's approval.

+++ Agent notes

  • Versions: fumadocs-ui 16.19.0, fumadocs-core 16.19.0, fumadocs-openapi 12.6.1, shiki 4.6.0, Next 16.4.5, React 19.2.7.
  • Upstream Highlighted only suspends or wraps in Suspense when highlighter.loadLanguage exists. fumadocs-openapi's own default highlighter already uses createDynamicCodeBlock.
  • Check that the Highlighter type accepts a missing loadLanguage. If it does not, use a thin adapter with no cast that throws away types.
  • Remove the async shiki factory and the void highlighter.loadLanguage(...) preload.
  • Browser measurement is not possible on the agent machine: headless Chromium is missing libnspr4.so. Use DevTools with Slow 4G and 4x CPU throttle, or Rendering > Paint flashing, on a preview.
  • Related: DOCS-1907 (done, fix(docs-next): keep API sample tabs highlighted when switching #413).

+++

Review in Linear

…test

The shown panel lookup could be undefined, which failed the typecheck.

Assisted-by: AI
@nickvigilante
nickvigilante marked this pull request as ready for review December 4, 2026 20:42
@nickvigilante
nickvigilante requested a review from a team as a code owner December 4, 2026 20:43

@Jesswinters Jesswinters left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean, small change. Removing the Suspense fallback and the $RC swaps by dropping loadLanguage is a neat fix, the comments explain the why, and the two new tests pin the behaviour on both the client and the server. CI is green. I found no blocking issues.

Approving the code. Your own merge gate still applies: please do the browser timing check in QA before merging. The preview deploy is still waiting for approval, so nobody can run that check yet.

Suggestions (P2)

  • The chunk numbers don't agree. The PR body gives three sets of figures for the operation-page chunk:

    • Merge order: about 111 KB gzipped moved into the chunk.
    • QA step 3: about 107 KB to 183 KB gzipped.
    • Benchmark: about 108 KB moved, and the chunk grows from 152 KB to 263 KB gzipped.

    Please pick one set (or say which build each comes from). Otherwise whoever runs the QA check won't know what result to expect.

  • Hydration cost is the main risk. The client now tokenizes all five samples synchronously during hydration. In Node, a cold run took about 180 ms in total, and a throttled mobile CPU will be slower than that. Lighthouse showed no change in mobile TBT, which is reassuring. During the QA check, look for a long task around hydration on the larger real operation pages, not only the fixture. If one shows up, the server-component approach you described is the fix.

Nits (P3, optional)

  • core.getLoadedLanguages() runs on every highlight. You could compute it once into a Set at module level. The cost is tiny either way.
  • An unknown language now quietly renders as plain text. A console.warn in development would make a future new sample language easy to spot. The old preload code had a similar warning.
  • The two new tests only work if they run first in the file. The comment explains this, which is good. Moving them into their own test file would make that guarantee structural, so a test added above them later can't break it.

Coder Agents generated this review for @Jesswinters.

This branch is waiting to be deployed

1 inactive and 1 waiting deployments
docs-preview — f2a76c8e Waiting Dec 4, 2026 by nickvigilante via preview / deploy preview #160
Preview — f2a76c8e Deployed Dec 4, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants