fix(start): initialize serialization adapters for early client server… #7708
main fromfix-7706·opened … functions
fixes #7706
Summary by CodeRabbit#
Bug Fixes
- Fixed server functions called from client entry modules before hydration, improving support for custom serialization adapters and server-function fetch settings.
- Improved early initialization so client-side server function calls work more reliably during app startup.
Tests
- Added end-to-end coverage for client-entry server-function serialization with nested return values.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-server-core
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-client-core
View your CI Pipeline Execution ↗ for commit 85cabb9ea980f7648982c0870cc84f2c93808142
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...❌ Failed 11m 58s View ↗ nx run-many --target=build --exclude=examples/*...❌ Failed 2m 18s View ↗
☁️ Nx Cloud last updated this comment at
2026-06-27 17:29:43UTC🚀 Changeset Version Preview#
2 package(s) bumped directly, 12 bumped as dependents.
🟩 Patch bumps#
Package Version Reason @tanstack/start-client-core1.170.12 → 1.170.13 Changeset @tanstack/start-server-core1.169.15 → 1.169.16 Changeset @tanstack/react-start1.168.26 → 1.168.27 Dependent @tanstack/react-start-client1.168.14 → 1.168.15 Dependent @tanstack/react-start-rsc0.1.25 → 0.1.26 Dependent @tanstack/react-start-server1.167.20 → 1.167.21 Dependent @tanstack/solid-start1.168.26 → 1.168.27 Dependent @tanstack/solid-start-client1.168.14 → 1.168.15 Dependent @tanstack/solid-start-server1.167.20 → 1.167.21 Dependent @tanstack/start-plugin-core1.171.18 → 1.171.19 Dependent @tanstack/start-static-server-functions1.167.17 → 1.167.18 Dependent @tanstack/vue-start1.168.25 → 1.168.26 Dependent @tanstack/vue-start-client1.167.17 → 1.167.18 Dependent @tanstack/vue-start-server1.167.20 → 1.167.21 Dependent Bundle Size Benchmarks#
- Commit:
8d37346a6638 - Measured at:
2026-06-27T17:18:50.223Z - Baseline source:
history:ba52d2b8f9e9 - Dashboard: bundle-size history
Scenario Current (gzip) Delta vs baseline Initial gzip Raw Brotli Trend react-router.minimal87.33 KiB 0 B (0.00%) 87.19 KiB 273.80 KiB 76.00 KiB ▁▁▁▁▁▁▁████ react-router.full91.06 KiB 0 B (0.00%) 90.92 KiB 285.70 KiB 79.10 KiB ▁▁▁▁▁▁▁████ solid-router.minimal35.53 KiB 0 B (0.00%) 35.40 KiB 106.00 KiB 31.98 KiB ▁▁▁▁▁▁▁████ solid-router.full40.58 KiB 0 B (0.00%) 40.46 KiB 121.22 KiB 36.50 KiB ▁▁▁▁▁▁▁████ vue-router.minimal53.01 KiB 0 B (0.00%) 52.88 KiB 150.04 KiB 47.68 KiB ▁▁▁▁▁▁▁████ vue-router.full58.99 KiB 0 B (0.00%) 58.86 KiB 168.80 KiB 52.88 KiB ▁▁▁▁▁▁▁████ react-start.minimal102.00 KiB +12 B (+0.01%) 101.86 KiB 322.30 KiB 88.27 KiB ▁▁▁▁▁▁▁▄▄▄▇█ react-start.deferred-hydration102.74 KiB +14 B (+0.01%) 101.88 KiB 323.68 KiB 89.03 KiB ▁▁▁▁▁▁▁▄▄▄▇█ react-start.full105.42 KiB +20 B (+0.02%) 105.28 KiB 332.29 KiB 91.22 KiB ▁▁▁▁▁▁▁▄▄▄▇█ react-start.rsbuild.minimal99.71 KiB +17 B (+0.02%) 99.54 KiB 316.73 KiB 85.84 KiB ▁▁▁▁▁▁▁▄▃▃▇█ react-start.rsbuild.minimal-iife100.11 KiB +14 B (+0.01%) 99.94 KiB 317.66 KiB 86.23 KiB ▁▁▁▁▁▁▁▄▃▃▇█ react-start.rsbuild.full102.94 KiB +24 B (+0.02%) 102.77 KiB 326.87 KiB 88.59 KiB ▁▁▁▁▁▁▁▄▃▃▆█ solid-start.minimal49.70 KiB +26 B (+0.05%) 49.57 KiB 152.25 KiB 43.91 KiB ▁▁▁▁▁▁▁▄▄▄▆█ solid-start.deferred-hydration52.96 KiB +24 B (+0.04%) 49.62 KiB 160.28 KiB 46.84 KiB ▁▁▁▁▁▁▁▄▄▄▆█ solid-start.full55.53 KiB +43 B (+0.08%) 55.40 KiB 169.35 KiB 48.93 KiB ▁▁▁▁▁▁▁▃▃▃▆█ vue-start.minimal71.12 KiB +7 B (+0.01%) 70.99 KiB 207.36 KiB 62.91 KiB ▁▁▁▁▁▁▁▅▅▅██ vue-start.full75.13 KiB +37 B (+0.05%) 75.00 KiB 220.06 KiB 66.45 KiB ▁▁▁▁▁▁▁▄▄▄▆█ Current gzip tracks all emitted client JS chunks. Initial gzip tracks only the entry/import graph. Trend sparkline is historical current gzip ending with this PR measurement; lower is better.
- Commit:
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/start-client-core/src/client/hydrateStart.ts (1)
21-30: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winClone the adapter list before merging router adapters.
serializationAdaptersreferences cachedstartOptions.serializationAdapters, sopush()mutates module-level Start options used later by client RPC serialization. Build a combined array instead, ideally deduping router adapters already present after retries/HMR.Proposed fix
- const startOptions = (await initStartOptions()) as AnyStartInstanceOptions - const serializationAdapters = startOptions.serializationAdapters - - if (router.options.serializationAdapters) { - serializationAdapters.push(...router.options.serializationAdapters) - } + const startOptions = + ((await initStartOptions()) ?? {}) as AnyStartInstanceOptions + const startSerializationAdapters = startOptions.serializationAdapters ?? [] + const routerSerializationAdapters = + router.options.serializationAdapters?.filter( + (adapter) => !startSerializationAdapters.includes(adapter), + ) ?? [] + const serializationAdapters = [ + ...startSerializationAdapters, + ...routerSerializationAdapters, + ] router.update({ basepath: process.env.TSS_ROUTER_BASEPATH, - ...{ serializationAdapters }, + serializationAdapters, })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-client-core/src/client/hydrateStart.ts` around lines 21 - 30, Clone the adapter list in hydrateStart before merging router adapters: startOptions.serializationAdapters is being reused directly, so the push in the router.options.serializationAdapters branch mutates cached Start options. In hydrateStart, build a new combined array from startOptions.serializationAdapters and router.options.serializationAdapters, and pass that copy into router.update. Also ensure duplicate adapters are not re-added when hydrateStart runs again (for retries/HMR) by deduping based on adapter identity before updating the router.🧹 Nitpick comments (2)
e2e/react-start/serialization-adapters/src/client.tsx (1)
39-44: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winType the rejection as
unknownbefore reading error fields.Promise.catchgives you an untyped rejection here, soerror?.name/error?.messagesidestep the strict-safety rule for this.tsxfile. Narrow it first and build the error payload from a checked shape. As per coding guidelines,**/*.{ts,tsx}: Use TypeScript strict mode with extensive type safety.Proposed fix
- .catch((error) => { + .catch((error: unknown) => { + const name = error instanceof Error ? error.name : 'Error' + const message = error instanceof Error ? error.message : String(error) + window.__serializationAdapterClientEntryResult = { status: 'error', - name: error?.name ?? 'Error', - message: error?.message ?? String(error), + name, + message, } })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/react-start/serialization-adapters/src/client.tsx` around lines 39 - 44, The Promise.catch handler in client.tsx is reading `error?.name` and `error?.message` from an untyped rejection, which violates strict type safety; update the catch in the client entry flow to treat the rejection as `unknown` first, then narrow it with a checked shape before building `window.__serializationAdapterClientEntryResult`. Use the existing catch block in the client entry logic to extract `name` and `message` only after validation, and fall back safely for non-error values.Source: Coding guidelines
e2e/react-start/serialization-adapters/tests/app.spec.ts (1)
86-90: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAvoid
window as anyin the test predicate.This drops type safety in the one place the spec reads the browser-side contract it is asserting. A small local type for the result shape keeps the wait predicate and the final assertion aligned. As per coding guidelines,
**/*.{ts,tsx}: Use TypeScript strict mode with extensive type safety.Proposed fix
+type ClientEntryServerFnResult = + | { + status: 'success' + ping: string + shout: string + whisper: string + } + | { + status: 'error' + name: string + message: string + } + const result = await page .waitForFunction( - () => (window as any).__serializationAdapterClientEntryResult, + () => + ( + window as Window & { + __serializationAdapterClientEntryResult?: ClientEntryServerFnResult + } + ).__serializationAdapterClientEntryResult, ) - .then((handle) => handle.jsonValue()) + .then((handle) => handle.jsonValue() as Promise<ClientEntryServerFnResult>)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/react-start/serialization-adapters/tests/app.spec.ts` around lines 86 - 90, The test predicate in app.spec.ts is bypassing type safety by using window as any when reading __serializationAdapterClientEntryResult. Replace that cast with a small local TypeScript type that describes the browser-side result shape, and use it both in the waitForFunction predicate and the final jsonValue/assertion so they stay aligned. Keep the change scoped to the existing page.waitForFunction flow and the __serializationAdapterClientEntryResult contract.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/start-client-core/src/client-rpc/serverFnFetcher.ts`: - Around line 114-116: The seroval plugin cache in serverFnFetcher should not be initialized with a one-time fallback because it can lock in stale adapters from the first call. Update the logic around getDefaultSerovalPlugins and serovalPlugins so it recomputes or refreshes based on the current startOptions instead of using ||=, and avoid module-level shared state that can leak across concurrent calls. Make sure the behavior still works with hydrateStart mutating serializationAdapters before later fetches. In `@packages/start-client-core/src/getDefaultSerovalPlugins.ts`: - Around line 9-11: `getDefaultSerovalPlugins` currently declares `start` as `AnyStartInstanceOptions | undefined`, which still forces callers to pass an argument and breaks the zero-arg uses in `staticFunctionMiddleware`. Update the function signature in `getDefaultSerovalPlugins` to make `start` optional with `start?: AnyStartInstanceOptions`, and keep the existing handling inside the function compatible with an omitted value. In `@packages/start-server-core/src/server-functions-handler.ts`: - Around line 70-72: The plugin cache in handleServerAction is incorrectly shared across requests, so it only reflects the first startOptions/serializationAdapters it sees. Remove the module-level serovalPlugins reuse and make the plugin list request-scoped by computing it from the current startOptions inside handleServerAction for each call, or otherwise key the cache by the incoming options. Keep the fix centered around handleServerAction and getDefaultSerovalPlugins so each request gets the correct server plugin set. --- Outside diff comments: In `@packages/start-client-core/src/client/hydrateStart.ts`: - Around line 21-30: Clone the adapter list in hydrateStart before merging router adapters: startOptions.serializationAdapters is being reused directly, so the push in the router.options.serializationAdapters branch mutates cached Start options. In hydrateStart, build a new combined array from startOptions.serializationAdapters and router.options.serializationAdapters, and pass that copy into router.update. Also ensure duplicate adapters are not re-added when hydrateStart runs again (for retries/HMR) by deduping based on adapter identity before updating the router. --- Nitpick comments: In `@e2e/react-start/serialization-adapters/src/client.tsx`: - Around line 39-44: The Promise.catch handler in client.tsx is reading `error?.name` and `error?.message` from an untyped rejection, which violates strict type safety; update the catch in the client entry flow to treat the rejection as `unknown` first, then narrow it with a checked shape before building `window.__serializationAdapterClientEntryResult`. Use the existing catch block in the client entry logic to extract `name` and `message` only after validation, and fall back safely for non-error values. In `@e2e/react-start/serialization-adapters/tests/app.spec.ts`: - Around line 86-90: The test predicate in app.spec.ts is bypassing type safety by using window as any when reading __serializationAdapterClientEntryResult. Replace that cast with a small local TypeScript type that describes the browser-side result shape, and use it both in the waitForFunction predicate and the final jsonValue/assertion so they stay aligned. Keep the change scoped to the existing page.waitForFunction flow and the __serializationAdapterClientEntryResult contract.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
4a3f9a71-fce9-4c62-9871-929251eaefb8📥 Commits
Reviewing files that changed from the base of the PR and between bb2daa6952f3689684b0cb6e4bd5f726fcbf8f42 and 85cabb9ea980f7648982c0870cc84f2c93808142.
📒 Files selected for processing (14)
.changeset/calm-adapters-serialize.mde2e/react-start/serialization-adapters/src/client-entry-server-functions.tse2e/react-start/serialization-adapters/src/client.tsxe2e/react-start/serialization-adapters/tests/app.spec.tspackages/router-core/src/index.tspackages/start-client-core/src/client-rpc/createClientRpc.tspackages/start-client-core/src/client-rpc/serverFnFetcher.tspackages/start-client-core/src/client/hydrateStart.tspackages/start-client-core/src/createServerFn.tspackages/start-client-core/src/getDefaultSerovalPlugins.tspackages/start-client-core/src/getStartOptions.tspackages/start-client-core/src/global.tspackages/start-server-core/src/createStartHandler.tspackages/start-server-core/src/server-functions-handler.ts
💤 Files with no reviewable changes (1)
- packages/start-client-core/src/global.ts
@@ -110,8 +111,6 @@110111 export async function serverFnFetcher(111112 url: string,112113 args: Array<any>,113- handler: (url: string, requestInit: RequestInit) => Promise<Response>,114+ startOptions: AnyStartInstanceOptions | undefined,114115 ) {115- if (!serovalPlugins) {116- serovalPlugins = getDefaultSerovalPlugins()117- }116+ serovalPlugins ||= getDefaultSerovalPlugins(startOptions)🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Don't freeze client seroval plugins on the first call.
serovalPlugins ||= ...snapshots the adapters from the first invocation.packages/start-client-core/src/client/hydrateStart.ts:19-32later mutatesstartOptions.serializationAdapters, so any pre-hydration call can leave this fetch path permanently missing adapters added during hydration. Since this function is async, the module-level cache also creates cross-call leakage if differentstartOptionsare observed concurrently.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-client-core/src/client-rpc/serverFnFetcher.ts` around lines 114 - 116, The seroval plugin cache in serverFnFetcher should not be initialized with a one-time fallback because it can lock in stale adapters from the first call. Update the logic around getDefaultSerovalPlugins and serovalPlugins so it recomputes or refreshes based on the current startOptions instead of using ||=, and avoid module-level shared state that can leak across concurrent calls. Make sure the behavior still works with hydrateStart mutating serializationAdapters before later fetches.@@ -2,9 +2,10 @@22 makeSerovalPlugin,33 defaultSerovalPlugins as routerDefaultSerovalPlugins,44 } from '@tanstack/router-core'5-import { getStartOptions } from './getStartOptions'65 import type { AnySerializationAdapter } from '@tanstack/router-core'6+import type { AnyStartInstanceOptions } from './createStart'77 import type { Plugin } from 'seroval'889-export function getDefaultSerovalPlugins(): Array<Plugin<any, any>> {10- const start = getStartOptions()9+export function getDefaultSerovalPlugins(10+ start: AnyStartInstanceOptions | undefined,11+): Array<Plugin<any, any>> {🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash rg -n --type=ts '\bgetDefaultSerovalPlugins\s*\(' packagesRepository: TanStack/router
Length of output: 773
🏁 Script executed:
#!/bin/bash sed -n '1,80p' packages/start-client-core/src/getDefaultSerovalPlugins.ts printf '\n---\n' sed -n '88,132p' packages/start-static-server-functions/src/staticFunctionMiddleware.ts printf '\n---\n' sed -n '100,130p' packages/start-client-core/src/client-rpc/serverFnFetcher.ts printf '\n---\n' sed -n '60,90p' packages/start-server-core/src/server-functions-handler.tsRepository: TanStack/router
Length of output: 3520
Make
startoptional.AnyStartInstanceOptions | undefinedstill requires an argument, so the zero-arg calls inpackages/start-static-server-functions/src/staticFunctionMiddleware.ts:100and:123don’t match this signature.start?: AnyStartInstanceOptionsaligns with the existing call sites.Proposed fix
export function getDefaultSerovalPlugins( - start: AnyStartInstanceOptions | undefined, + start?: AnyStartInstanceOptions, ): Array<Plugin<any, any>> {📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change9-export function getDefaultSerovalPlugins(10- start: AnyStartInstanceOptions | undefined,11-): Array<Plugin<any, any>> {9+export function getDefaultSerovalPlugins(10+ start?: AnyStartInstanceOptions,11+): Array<Plugin<any, any>> {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-client-core/src/getDefaultSerovalPlugins.ts` around lines 9 - 11, `getDefaultSerovalPlugins` currently declares `start` as `AnyStartInstanceOptions | undefined`, which still forces callers to pass an argument and breaks the zero-arg uses in `staticFunctionMiddleware`. Update the function signature in `getDefaultSerovalPlugins` to make `start` optional with `start?: AnyStartInstanceOptions`, and keep the existing handling inside the function compatible with an omitted value.@@ -66,4 +69,4 @@66696770 // Initialize serovalPlugins lazily (cached at module level)6871 if (!serovalPlugins) {69- serovalPlugins = getDefaultSerovalPlugins()72+ serovalPlugins = getDefaultSerovalPlugins(startOptions)🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Make the server plugin list request-scoped.
handleServerActionnow receivesstartOptionsper call, but this cache only honors the first one. Later requests or handler instances with differentserializationAdapterswill still use the first plugin set.Proposed fix
- if (!serovalPlugins) { - serovalPlugins = getDefaultSerovalPlugins(startOptions) - } + const serovalPlugins = getDefaultSerovalPlugins(startOptions)📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change70- // Initialize serovalPlugins lazily (cached at module level)71- if (!serovalPlugins) {72- serovalPlugins = getDefaultSerovalPlugins(startOptions)70+ // Initialize serovalPlugins lazily (cached at module level)71+ const serovalPlugins = getDefaultSerovalPlugins(startOptions)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-server-core/src/server-functions-handler.ts` around lines 70 - 72, The plugin cache in handleServerAction is incorrectly shared across requests, so it only reflects the first startOptions/serializationAdapters it sees. Remove the module-level serovalPlugins reuse and make the plugin list request-scoped by computing it from the current startOptions inside handleServerAction for each call, or otherwise key the cache by the incoming options. Keep the fix centered around handleServerAction and getDefaultSerovalPlugins so each request gets the correct server plugin set.Merging this PR will not alter performance#
:warning: Different runtime environments detected
Some benchmarks with significant performance changes were compared across different runtime environments, which may affect the accuracy of the results.
⚡ 3improved benchmarks❌ 2regressed benchmarks✅ 139untouched benchmarksWarning
Please fix the performance issues or acknowledge them on CodSpeed.
Performance Changes#
Mode Benchmark BASEHEADEfficiency ❌ Memory mem serialization-payload (vue)6.8 MB 9.5 MB -28.77% ❌ Memory mem serialization-payload (solid)6.8 MB 7.1 MB -3.3% ⚡ Memory mem aborted-requests (solid)2.4 MB 1.9 MB +24.03% ⚡ Memory mem peak-large-page (solid)3.9 MB 3.4 MB +14.19% ⚡ Memory mem aborted-requests (vue)1,021 KB 935.4 KB +9.15% Tip
Investigate this regression by commenting
@codspeedbot fix this regressionon this PR, or directly use the CodSpeed MCP with your agent.
Comparingfix-7706(85cabb9) withmain(ba52d2b)[^unexpected-base]Nx Cloud is proposing a fix for your failed CI:#
We updated
staticFunctionMiddleware.tsto passgetStartOptions()to both calls ofgetDefaultSerovalPlugins, fixing the TypeScript error introduced when the PR changed the function signature to require astartargument. This call site in@tanstack/start-static-server-functionswas the only one not updated alongside the refactor in@tanstack/start-client-core.Tip
✅ We verified this fix by re-running
@tanstack/start-static-server-functions:build,@tanstack/start-static-server-functions:test:types.Suggested Fix changes
diff --git a/packages/start-client-core/src/index.tsx b/packages/start-client-core/src/index.tsx index 5bf09c44..b322d19d 100644 --- a/packages/start-client-core/src/index.tsx +++ b/packages/start-client-core/src/index.tsx @@ -130,6 +130,7 @@ export type { Register } from '@tanstack/router-core' export { getRouterInstance } from './getRouterInstance' export { getDefaultSerovalPlugins } from './getDefaultSerovalPlugins' +export { getStartOptions } from './getStartOptions' export { getGlobalStartContext } from './getGlobalStartContext' export { safeObjectMerge, createNullProtoObject } from './safeObjectMerge' export { trackPostProcessPromise } from './client-rpc/serverFnFetcher' diff --git a/packages/start-static-server-functions/src/staticFunctionMiddleware.ts b/packages/start-static-server-functions/src/staticFunctionMiddleware.ts index e6681fce..f8cc6f06 100644 --- a/packages/start-static-server-functions/src/staticFunctionMiddleware.ts +++ b/packages/start-static-server-functions/src/staticFunctionMiddleware.ts @@ -3,6 +3,7 @@ import path from 'node:path' import { createMiddleware, getDefaultSerovalPlugins, + getStartOptions, } from '@tanstack/start-client-core' import { fromJSON, toJSONAsync } from 'seroval' @@ -97,7 +98,7 @@ async function addItemToCache({ result: response.result, context: response.context.sendContext, }, - { plugins: getDefaultSerovalPlugins() }, + { plugins: getDefaultSerovalPlugins(getStartOptions()) }, ), ) await fs.writeFile(filePath, stringifiedResult, 'utf-8') @@ -120,7 +121,9 @@ const fetchItem = async ({ method: 'GET', }) .then((r) => r.json()) - .then((d) => fromJSON(d, { plugins: getDefaultSerovalPlugins() })) + .then((d) => + fromJSON(d, { plugins: getDefaultSerovalPlugins(getStartOptions()) }), + ) return result }
Or Apply changes locally with:
Apply fix locally with your editor ↗ View interactive diff ↗npx nx-cloud apply-locally XqTW-a3TK
🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)Heads-up from the Solid 2 side: the rc line has its own manifestation of this bug that this PR does not currently reach. Flagging it now so the Solid path does not require a second issue/PR cycle after this merges.
@tanstack/solid-start@2.0.0-rc.3, fromsolid-router-v2-pre, ships its owncreateClientRpcover@solidjs/web/server-functions/client. (mainstill has Solid Start re-exporting the sharedstart-client-coreRPC implementation.)Solid 2 configures its codec while each compiled server-function stub is evaluated:
// packages/solid-start/src/client-rpc.ts configureServerFunctionsClient({ endpoint, codec: getSolidStartServerFunctionCodec(), }); // packages/solid-start/src/solid-rpc-codec.ts return { plugins: getDefaultSerovalPlugins() .filter // Remove the duplicate ReadableStream plugin (), };Those stub modules normally evaluate before hydration, so the codec's plugin list is frozen before
hydrateStart()publishes the Start options. Unlike the client-entry-only reproduction in #7706, later calls through those already-evaluated stubs also remain broken: customserializationAdaptersnever reach RPC encoding or decoding.In our app, 23 build-path e2e scenarios carrying
Temporal.PlainDatefailed at@tanstack/solid-start@2.0.0-rc.3/solid-js@2.0.0-rc.3with:SerovalDeserializationError: Missing plugin for tag "$TSR/t/PlainDate"None of this PR's
start-client-core/src/client-rpcorserverFnFetcherchanges are reached by the Solid 2 RPC path. If itsgetDefaultSerovalPlugins()signature change is ported to the rc branch, the current no-argument call will also require deliberate adaptation: passingundefinedwould still omit the app adapters, while callinggetStartOptions()during stub evaluation would hit the new pre-initialization invariant.The complete Solid 2 counterpart appears to require initializing/awaiting Start options in the invocation path before the
@solidjs/webreference serializes its arguments. BecauseconfigureServerFunctionsClientaccepts a static codec object, that likely means configuring it lazily on first invocation or supplying a codec whose plugins resolve lazily.We currently ship the latter as a
pnpm patch: aget plugins()accessor defersgetDefaultSerovalPlugins()until serialization time. The@solidjs/webconsumer readscodec.pluginsper serialization/deserialization, and this fixed all 23 failures; the full 300-test e2e suite then passed. That getter fixes our normal post-hydration calls, but a server function deliberately invoked from the client entry before hydration would additionally need theinitStartOptions()step described above.Happy to share a minimal reproduction or send a focused PR against
solid-router-v2-preif useful.schiller-manuel(GitHub profile, opens in a new tab) linked this to fix #7706
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
Introduces
initStartOptions()to lazily initialize and cache start options (including serialization adapters) at the module level, replacing thewindow.__TSS_START_OPTIONS__global. This allows server functions called from the client entry before hydration to access custom serialization adapters. The options are threaded through client RPC creation, middleware execution, seroval plugin selection, and server-side action handling.Changes#
Pre-hydration serialization adapter fix
initStartOptions,setStartOptions, andgetStartOptionsreworkpackages/start-client-core/src/getStartOptions.ts,packages/start-client-core/src/global.ts,packages/start-client-core/src/getDefaultSerovalPlugins.ts,packages/router-core/src/index.tsstartOptionsreplaceswindow.__TSS_START_OPTIONS__.setStartOptionswires serialization adapters. NewinitStartOptionsinitializes fromstartInstance(handling promise results) or creates empty options.getDefaultSerovalPluginsnow acceptsstartOptionsas a parameter.isPromiseis re-exported fromrouter-core.serverFnFetcherupdatedpackages/start-client-core/src/client-rpc/createClientRpc.ts,packages/start-client-core/src/client-rpc/serverFnFetcher.tscreateClientRpcreplaces synchronousgetStartOptions()withinitStartOptions()and adds Promise-aware branching.serverFnFetchersignature changes from ahandlerfetch function tostartOptions, using it for seroval plugin selection and fetch defaulting.hydrateStartpackages/start-client-core/src/createServerFn.ts,packages/start-client-core/src/client/hydrateStart.tsexecuteMiddlewaregains an explicitglobalMiddlewaresparameter. Client-side server function calls initializestartOptionsviainitStartOptions()and passfunctionMiddlewareexplicitly.hydrateStartawaitsinitStartOptions()instead of reading fromstartInstanceand writing to the window global.packages/start-server-core/src/createStartHandler.ts,packages/start-server-core/src/server-functions-handler.tshandleServerActionaccepts a newstartOptions: AnyStartInstanceOptionsparameter, used to derive seroval plugins per-request viagetDefaultSerovalPlugins(startOptions).e2e/react-start/serialization-adapters/src/client-entry-server-functions.ts,e2e/react-start/serialization-adapters/src/client.tsx,e2e/react-start/serialization-adapters/tests/app.spec.ts,.changeset/calm-adapters-serialize.mdEstimated code review effort#
🎯 4 (Complex) | ⏱️ ~50 minutes
Possibly related PRs#
serverFnFetcher.tsto change client server-function request/response processing, directly overlapping with this PR's changes to the same file's fetch selection and plugin initialization logic.Suggested labels#
package: start-client-core,package: start-server-core🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
#7706by initializing start options and serialization adapters before client-entry server function calls.✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.