Start: server function URL computed at module init from unreplaced `process.env.TSS_SERVER_FN_BASE`, yielding a relative RPC URL in dev #8201
Which project does this relate to?#
Start
Describe the bug#
createClientRpc() computes a server function's request URL at module evaluation time (packages/start-client-core/src/client-rpc/createClientRpc.ts):
export function createClientRpc(functionId: string) {
const url = process.env.TSS_SERVER_FN_BASE + functionId
// …
}
TSS_SERVER_FN_BASE is supplied as a Vite define (defineReplaceEnv() in start-plugin-core). During vite dev that define is not applied to files inside node_modules — the dev-served module still contains the literal process.env.TSS_SERVER_FN_BASE, and the value exists only because Vite's /@vite/env shim assigns globalThis.process.env at runtime. The URL is therefore only correct if /@vite/env has executed before the generated server-function module evaluates.
When it hasn't, url becomes the string "undefined" + functionId, which is a relative URL. The fetch then resolves against the current document path — e.g. /posts/1/undefinedsrc_utils_posts_tsx--fetchPost_createServerFn_handler — never matches TSS_SERVER_FN_BASE in createStartHandler, falls through to the router, and since serverFnFetcher sends accept: application/x-ndjson, application/json the router answers:
500 {"error":"Only HTML requests are supported here"}
serverFnFetcher rethrows that as new Error(await response.text()), so app authors see a bare Error whose message is raw JSON, thrown from whichever component happens to call a server function first — with nothing pointing at the real cause.
Two things make it look random rather than reproducible:
- it depends on module evaluation order, which shifts with dep-optimization state, HMR and import graph changes;
- a relative URL still resolves correctly on
/(undefined…→/undefined…is wrong but at the root there is no prefix to inherit), while on/foo/barit inherits the path. So the same app "works" on one page and fails on another.
Complete minimal reproducer#
https://stackblitz.com/github/tanstack/router/tree/main/examples/react/start-basic
No custom code is needed — the example's own server functions (src/utils/posts.tsx) are enough. Any Start app with a server function shows it.
Steps to Reproduce the Bug#
Start the dev server for the example above.
Confirm the define is not statically applied in dev — request the dev-served dependency module:
curl -s 'http://localhost:3000/@fs/<abs-path>/node_modules/@tanstack/start-client-core/dist/esm/client-rpc/createClientRpc.js' | grep TSS_SERVER_FN_BASEconst url = process.env.TSS_SERVER_FN_BASE + functionId; // unreplacedIn the browser,
process.env.TSS_SERVER_FN_BASEis a runtime property (Object.keys(globalThis.process.env)→TSS_CLIENT_OUTPUT_DIR, TSS_DEV_SERVER, TSS_ROUTER_BASEPATH, TSS_SERVER_FN_BASE, TSS_SHELL), i.e. it comes from the shim, not from a build-time replacement.Force the ordering that the shim normally hides. On any non-root route, in the browser console:
delete process.env.TSS_SERVER_FN_BASE const m = await import('/src/utils/posts.tsx?forcereeval=1') // fresh module instance await m.fetchPost({ data: '1' })Error: {"error":"Only HTML requests are supported here"} Network: GET /posts/undefinedsrc_utils_posts_tsx--fetchPost_createServerFn_handler?payload=…
Step 3 forces deterministically what module ordering otherwise decides by chance; the timing dependence is exactly why this surfaces intermittently in real apps rather than always.
Expected behavior#
A server function's request URL shouldn't depend on module evaluation order in dev — it should be absolute in every case.
A few directions (not prescriptive):
- compute
urllazily insideclientFn, so the read happens at call time, long after the dev shims are installed (urlis also exposed on the returned object, so a getter would preserve that); - or fall back to the configured default when the define is missing, instead of string-concatenating
undefined; - or read
import.meta.env.TSS_SERVER_FN_BASE—defineReplaceEnv()already defines both spellings, and Vite providesimport.meta.envper module in dev.
Separately, and regardless of which fix is chosen: a request that reaches the router with a non-HTML Accept currently reports as 500, which sent me looking for a server fault. See #7913 for that side of it.
Screenshots or Videos#
No response
Platform#
- Router / Start Version:
@tanstack/react-start1.133.3 — the relevant line is unchanged in@tanstack/start-client-core1.170.27, anddefineReplaceEnv/ the dev client-entry injection are unchanged too, so this is not fixed by upgrading - OS: macOS (darwin 25.6.0)
- Browser: Chrome / Chromium
- Bundler:
rolldown-vite(aliased asvite), Vite 7 dev server - Also present with
@cloudflare/vite-pluginas the SSR environment, though that is not needed to reproduce
Additional context#
Workaround for app authors until this is fixed — seed the value from an inline classic script in <head>, which runs while the head is parsed and therefore before any module script exists:
<script>globalThis.process ??= {}; globalThis.process.env ??= {}; globalThis.process.env.TSS_SERVER_FN_BASE ??= "/_serverFn/";</script>
??= yields to the real value whenever the shim wins the race anyway, and the snippet can be gated to dev so production keeps using the statically replaced define.
schiller-manuel(GitHub profile, opens in a new tab) added labelsinformation needed
You're right to push back, and my original reproducer deserved it — step 3 forced the condition it was meant to demonstrate, and the "Complete minimal reproducer" field pointed at
examples/react/start-basic, which does not exhibit this. Sorry for the noise.Here is a reproducer that needs no client-side JS, and the reason the example can't show it.
Why it normally can't happen#
With
@vitejs/plugin-reactthe dev HTML gets the refresh preamble, and Start's client entry is loaded from inside it:import { injectIntoGlobalHook } from "/@react-refresh"; // statically imports "/@vite/client" injectIntoGlobalHook(window); … import('/@id/virtual:tanstack-start-client-entry') // dynamic — runs after the above/@react-refreshline 1 isimport { injectQuery as __vite__injectQuery } from "/@vite/client", and/@vite/clientpulls in/@vite/env, which assignsglobalThis.process.env. Static imports are evaluated before the importing module's body, and the client entry is only reached through the dynamic import in that body. Soprocess.env.TSS_SERVER_FN_BASEis always set before any server-function module can evaluate.That ordering is a hard guarantee — but it comes from the React plugin, not from Start. Nothing in Start establishes it.
Reproducer#
@vitejs/plugin-reactdrops the preamble when HMR is off (packages/plugin-react/src/index.ts, theskipFastRefreshassignment):skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === falseSo:
- Take a Start app with a server function and
@vitejs/plugin-react. - Add to
vite.config.ts:server: { hmr: false } vite dev, open any route.
server.hmr: falseis an ordinary setting — containers, tunnels, reverse proxies where the HMR socket can't connect.Observed#
The preamble is gone from the HTML, nothing imports
/@vite/client, andglobalThis.processnever comes into existence:ReferenceError: process is not defined at createClientRpc (@tanstack/start-client-core/dist/esm/client-rpc/createClientRpc.js:4:15) at /src/lib/session.ts:3:49typeof globalThis.process === "undefined", and the app does not hydrate at all — every module that constructs a server function throws at evaluation.Note this is worse than what I originally described. I assumed
globalThis.process.envwould exist with the key missing, giving"undefined" + functionIdand a relative URL. Without the shimprocessitself is absent, so it's a hardReferenceErrorrather than a bad request.Scope#
Verified in our own Start app (TanStack Start +
@vitejs/plugin-react+@cloudflare/vite-plugin), toggling onlyserver.hmr. I have not runstart-basicitself withhmr: false— the mechanism is entirely in the plugin and the client-entry bootstrap, so I'd expect it there too, but I'm not going to claim it twice without checking.The framing I'd suggest, if it helps: this isn't really a race. It's that the correctness of a server function's URL depends on
@vitejs/plugin-reacthappening to emit a preamble that statically imports/@vite/client. Any setup without that preamble breaks — HMR disabled here, but the same would hold for a plugin whose preamble doesn't reach/@vite/client.The suggestions in the original report still apply; computing
urllazily insideclientFn, or readingimport.meta.env.TSS_SERVER_FN_BASE(whichdefineReplaceEnv()already defines and Vite provides per-module in dev), would make it independent of any of this.- Take a Start app with a server function and
You're right to push back, and my original reproducer deserved it — step 3 forced the condition it was meant to demonstrate, and the "Complete minimal reproducer" field pointed at
examples/react/start-basic, which does not exhibit this. Sorry for the noise.Here is a reproducer that needs no client-side JS, and the reason the example can't show it.
Why it normally can't happen#
With
@vitejs/plugin-reactthe dev HTML gets the refresh preamble, and Start's client entry is loaded from inside it:import { injectIntoGlobalHook } from "/@react-refresh"; // statically imports "/@vite/client" injectIntoGlobalHook(window); … import('/@id/virtual:tanstack-start-client-entry') // dynamic — runs after the above
/@react-refreshline 1 isimport { injectQuery as __vite__injectQuery } from "/@vite/client", and/@vite/clientpulls in/@vite/env, which assignsglobalThis.process.env. Static imports are evaluated before the importing module's body, and the client entry is only reached through the dynamic import in that body. Soprocess.env.TSS_SERVER_FN_BASEis always set before any server-function module can evaluate.That ordering is a hard guarantee — but it comes from the React plugin, not from Start. Nothing in Start establishes it.
Reproducer#
@vitejs/plugin-reactdrops the preamble when HMR is off (packages/plugin-react/src/index.ts, theskipFastRefreshassignment):skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false So:
- Take a Start app with a server function and
@vitejs/plugin-react. - Add to
vite.config.ts: server: { hmr: false } vite dev, open any route.
server.hmr: falseis an ordinary setting — containers, tunnels, reverse proxies where the HMR socket can't connect.Observed#
The preamble is gone from the HTML, nothing imports
/@vite/client, andglobalThis.processnever comes into existence:ReferenceError: process is not defined at createClientRpc (@tanstack/start-client-core/dist/esm/client-rpc/createClientRpc.js:4:15) at /src/lib/session.ts:3:49typeof globalThis.process === "undefined", and the app does not hydrate at all — every module that constructs a server function throws at evaluation.Note this is worse than what I originally described. I assumed
globalThis.process.envwould exist with the key missing, giving"undefined" + functionIdand a relative URL. Without the shimprocessitself is absent, so it's a hardReferenceErrorrather than a bad request.Scope#
Verified in our own Start app (TanStack Start +
@vitejs/plugin-react+@cloudflare/vite-plugin), toggling onlyserver.hmr. I have not runstart-basicitself withhmr: false— the mechanism is entirely in the plugin and the client-entry bootstrap, so I'd expect it there too, but I'm not going to claim it twice without checking.The framing I'd suggest, if it helps: this isn't really a race. It's that the correctness of a server function's URL depends on
@vitejs/plugin-reacthappening to emit a preamble that statically imports/@vite/client. Any setup without that preamble breaks — HMR disabled here, but the same would hold for a plugin whose preamble doesn't reach/@vite/client.The suggestions in the original report still apply; computing
urllazily insideclientFn, or readingimport.meta.env.TSS_SERVER_FN_BASE(whichdefineReplaceEnv()already defines and Vite provides per-module in dev), would make it independent of any of this.Thank you for the additional clarification and for the considerable expenditure of explanatory effort represented by the preceding response. Before proceeding further with the underlying technical question, it may be useful to establish a more explicit shared understanding concerning the relationship between the quantity of information supplied, the extent to which that information is necessary for the immediate decision being made, and the finite amount of maintainer attention available for converting the supplied information into an actionable conclusion.
For the avoidance of doubt, the concern being raised here is not that factual accuracy, reproducibility, technical precision, correction of earlier assertions, or sufficient evidentiary support are undesirable. Each of those properties is useful and may, under the appropriate circumstances, be necessary. The difficulty arises when the information required to establish the relevant fact is accompanied by additional explanation whose presence, although potentially interesting and perhaps even technically correct, does not materially alter the fact itself, the confidence with which that fact can be evaluated, or the action that follows from accepting it.
Every response imposes what might be described as a comprehension obligation upon its recipients. That obligation consists not merely of reading the words presented, but also of determining which statements constitute factual claims, which function as evidence, which are qualifications, which are conjectures, which supersede earlier statements, which merely restate conclusions already established elsewhere, and which are included primarily to explain the circumstances under which some other statement came to be made. The cost of satisfying this obligation tends to increase with the length, density, and structural complexity of the response, even where the amount of information capable of changing the maintainer’s eventual decision remains constant.
This consideration is particularly significant in the context of open-source maintenance, where the time required to read, classify, verify, and contextualize one response cannot simultaneously be used to reproduce another issue, review a pull request, investigate a regression, prepare a release, answer another contributor, evaluate a dependency update, improve documentation, or perform any of the numerous other activities competing for the same limited pool of attention. Consequently, verbosity is not entirely without cost merely because the information is supplied voluntarily, constructively, and with the intention of preventing misunderstanding. Its cost is transferred to each recipient who must determine which portions are operationally necessary and which portions can be disregarded without compromising the validity of the resulting conclusion.
We would therefore ask that future responses be prepared according to something approximating a principle of minimum sufficient communication, by which a response contains the smallest collection of independently useful facts required to answer the question currently being asked or to establish the behavior currently under discussion. Information should not be included solely because it is adjacent to the subject, because it records the path by which a conclusion was reached, because it anticipates questions that have not yet been asked, because it exhaustively delineates the boundaries of claims whose ordinary interpretation is already sufficiently narrow, or because omitting it might leave some peripheral aspect of the subject less than comprehensively characterized.
The use of the word “smallest” in this context should not be interpreted as a request for artificial abbreviation, unexplained assertions, incomplete reproduction instructions, or the omission of facts required to distinguish the reported behavior from another superficially similar behavior. It means, instead, that each sentence should justify the attention required to process it by contributing something without which a maintainer would be materially less able to verify the report or determine the appropriate next action. Where the removal of a sentence would leave the actionable meaning unchanged, that sentence should generally be presumed removable. Where several paragraphs can be replaced by a single concrete observation without sacrificing reproducibility, the concrete observation should be preferred. Where a mechanism can be demonstrated through a minimal configuration change and an immediately observable result, that demonstration should ordinarily take precedence over a comprehensive narrative describing the mechanism’s provenance, implications, surrounding implementation details, and hypothetical manifestations in configurations not yet tested.
Qualifications should similarly be restricted to those that alter the reasonable interpretation of the principal claim. It is generally unnecessary to enumerate every proposition that is not being asserted, every environment that has not been tested, every alternative explanation that was considered and rejected, every inference that a sufficiently careful reader might otherwise draw, or every reason the author has for believing that an untested configuration may behave similarly. Where uncertainty is relevant, it is usually sufficient to identify the precise boundary of verification rather than narrating the broader epistemological status of all related propositions.
One potentially useful standard for deciding whether information warrants inclusion is to ask whether the behavior that actually occurs, the smallest reliable procedure that causes it to occur, and any qualification without which those statements would become materially misleading remain understandable and reproducible after the information is removed. If they do, the removed material was probably not necessary for the immediate response. Background already available elsewhere in the issue, detailed explanations of standard language or bundler behavior, speculative generalizations beyond the verified reproducer, extended discussion of why an earlier reproducer was inadequate, descriptions of investigative paths that did not produce the final result, and multiple reformulations of the same conclusion at successively different levels of abstraction should normally be retained by the author unless and until a maintainer requests them.
This request is not intended as a judgment concerning the effort, competence, thoroughness, or good faith involved in preparing the response. It concerns the format in which the result of that effort is presented. A technically correct response may nevertheless be disproportionately expensive to consume, in much the same way that a comprehensive diagnostic log may contain the relevant error while simultaneously making that error more difficult to locate. The objective is not to minimize the amount of investigation performed by the reporter, but to minimize the portion of that investigation which every subsequent reader must reconstruct before reaching the actionable result.
We recognize that determining what is essential requires judgment and that contributors cannot invariably know in advance which detail a maintainer will consider relevant. In such circumstances, the preferred strategy is progressive disclosure, under which the shortest adequately supported factual answer is provided initially and further supporting detail is supplied only when a maintainer identifies a concrete need for it. It is substantially easier for a maintainer to request one missing fact than it is for multiple maintainers to independently identify and disregard several pages of facts that do not affect the decision being made.
The appropriate optimization target is therefore not maximum completeness at the time of the first response, but minimum aggregate effort across all participants required to reach a sufficiently supported conclusion. A concise response that results in one targeted follow-up question may satisfy that target more effectively than an exhaustive response which attempts to preempt every conceivable follow-up but requires substantially greater processing time from every reader, including readers for whom most of the anticipated questions would never have arisen.
Facts directly necessary to establish the reported behavior should be included. Evidence directly necessary to verify those facts should be included only to the extent that verification would otherwise be impractical or ambiguous. Context that may be interesting but does not change the facts, their verification, or the resulting action should be omitted unless specifically requested. Where several formulations communicate materially identical information, the shortest formulation should be selected. Where a direct statement is available, it should take precedence over a narrative account of how the statement was discovered. Where one verified claim is sufficient, it should not be surrounded by multiple hypothetical extensions. Where the answer to a question can be expressed as a concrete condition and an observable consequence, the response should ordinarily contain that condition and consequence without attempting to supply a general theory of every adjacent failure mode.
It is also important to clarify that this does not mean providing a concise summary followed by the same extended explanation that the summary was intended to replace. The continued presence of the explanation preserves most of the reading, classification, and triage cost. A summary is not a substitute for removing unnecessary material when the unnecessary material remains directly beneath it. Supporting details can remain available to the author and can be supplied in a subsequent response if a maintainer determines that the initial facts are insufficient.
Nor is it generally necessary to surround relevant facts with introductory courtesies, repeated apologies, rhetorical transitions, anticipatory defenses, summaries of prior misunderstandings, explanations of why the current answer differs from a previous answer, assurances about claims that are not being made, or concluding restatements of conclusions already expressed. Courtesy is appreciated, but its communicative footprint need not substantially exceed that of the technical substance. A correction is most useful when it makes the corrected claim immediately identifiable and permits the obsolete claim to be discarded without requiring the reader to reconstruct the entire history of the correction.
Applied to the present exchange, the information that appears most capable of affecting maintainer action is that disabling HMR removes the React refresh preamble, that the resulting client bootstrap no longer causes the relevant environment initialization to occur before
createClientRpcis evaluated, and that server-function construction consequently encounters aReferenceErrorbecauseprocessis unavailable. The precise import-order mechanics, the contrast with the initial theory concerning a relative URL, the implications for other plugins whose preambles may differ, the explanation of why the originally linked example does not exhibit the behavior under its default configuration, and the broader characterization of the problem as a dependency on an incidental ordering guarantee may become relevant during implementation, but they need not all be transmitted before maintainers have had an opportunity to evaluate the narrower verified condition and its immediate consequence.In consideration of the asymmetry between the effort required for an author to preserve additional material and the cumulative effort required for every recipient to inspect and classify that material, and with due regard for the limited and nonrenewable character of volunteer maintainer attention as it relates to the substantially renewable supply of potentially relevant contextual exposition, future participation would be most effective if each response were reduced, before submission, to only those empirically established statements whose omission would prevent reproduction, materially distort the reported behavior, or leave the specific question under consideration unanswered, with all supplementary narrative, speculative extension, duplicative reformulation, historical reconstruction, rhetorical cushioning, and otherwise nonessential elaboration withheld pending an explicit indication that its disclosure is required.
- Take a Start app with a server function and
Sign in to join this conversation.
please provide an actual reproducer project that exhibits this issue without having to execute some client-side JS, just by normal usage.