Repository navigation
Description
Which project does this relate to?
Start
Describe the bug
Calling a serverFn using middleware in the client with useServerFn results in server side code being included in client bundle.
I'll try to get a minimal reproduction later this weekend or early next week. But here is an example of the issue.
Your Example Website or App
In this example, app/routes/index.tsx contains an client only middleware that causes the issue. If you uncomment the server section the error will go away.
Steps to Reproduce the Bug or Issue
Basic Example:
import { getSupabaseServerClient } from "@/features/supabase/utils";
import { createServerFn, createMiddleware } from "@tanstack/start";
import { useQuery } from "@tanstack/react-query";
import { z } from 'zod'
export const authMiddleware = createMiddleware().server(async ({ next }) => {
const supa = getSupabaseServerClient();
const user = await supa.auth.getUser();
return next({ context: { user } });
});
const serverFilters = z.object({ })
const getQuery = createServerFn({ method: "GET" })
.middleware([authMiddleware])
.validator((input: unknown) => serverFilters.parse(input))
.handler(async ({ data, context }) => {
...
});
function useQueryData(data: any) {
const getData = useServerFn(getQuery);
return useQuery({
queryKey: ["id", JSON.stringify(filters)],
queryFn: () => getData({ data: filters }),
});
}Client Side Error:
I see a request for the file "@/features/supabase/utils", and get this console error.
Uncaught Error: Module "node:async_hooks" has been externalized for browser compatibility. Cannot access "node:async_hooks.AsyncLocalStorage" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
get __vite-browser-external:node:async_hooks:3
<anonymous> http.js:71
[__vite-browser-external:node:async_hooks:3:10](http://localhost:3000/_build/@id/__vite-browser-external:node:async_hooks)
Expected behavior
No error & the file "@/features/supabase/utils" is not included in client side code.
Removing the middleware from the server function resolves the issue. The same reference to getSupbaseServerClient inside the serverFn handler runs without issue.
Screenshots or Videos
No response
Platform
- OS: macOS
- Browser: Firefox
- Version: 1.81.15
- Server Preset: Node-Server
Additional context
No response
Activity
SeanCassiere commentedon Nov 16, 2024
From a cursory overview, it seems that dead-code-elimination isn't being performed on the client references code before being packaged into their necessary bundles.
router/packages/start-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx
Lines 12 to 21 in 5589151
dotnize commentedon Nov 17, 2024
What worked for me was moving the middleware definition (createMiddleware) into its own separate file
SeanCassiere commentedon Nov 18, 2024
I'm having difficult reproducing this using our "start-supabase-basic" example.
scrawfor commentedon Nov 18, 2024
@SeanCassiere - I'll try to pull together a reproduction tomorrow. I attempted yesterday but I was having issues with StackBlitz.
I will say my example was overly simplistic. I actually had the Middleware in a separate file. Tonight I tried defining the middleware in the same file as the server function and that worked. The contents of the middleware were the same in both cases.
scrawfor commentedon Nov 18, 2024
@SeanCassiere - I've created a reproduction on StackBlitz. This example handles it more gracefully than my actual case (where the route crashes and burns), but it still reproduces. If you open your browser dev tools, the console should show node-related errors and also load server side packages
I reproduced it with two separate middleware functions using two separate node packages. I added the server function with middleware to
app/routes/index.tsx.First Reproduction
The first is using supabase as mentioned above.
features/supabase.tscreates a supbase client and anauthMiddleware. This authMiddleware doesn't actually do anything, but it's defined in the same file as the supabase code. Importing it will cause the errors mentioned above.Second Reproduction
The second reproduction is in
features/db.ts. It defines a dbMiddleware that adds a clickhouse client to the context. Uncomment.middleware([dbMiddlware])fromapp/routes/index.tsx. This results in a slightly different console error, but the root cause is the same. The Clickhouse client is pulled into client side code. If the samedbMilddlewarecode is instead defined inapp/routes/indexthis doesn't break.dan-gamble commentedon Dec 5, 2024
I'm getting this issue even with it being done all this way. Is there a way to "fix" this until a proper resolution is in place?Removing this middleware does remove the console error.Seems like it's just the
getEventin theshopNameSchema. I imagine this is finding it's way into a client package somehow__root.tsx
app/middleware/shopify/validate-search-params-middleware.tsx
JohnnyCrazy commentedon Dec 26, 2024
Just to add some observations to that: It seems like that it's also important to not export any server side functions, as this will also lead them to being imported in the client package, even if defined in the same route.
So for example, this works:
but this doesn't:
Can create a minimal example if needed
leonlarsson commentedon Jan 3, 2025
Experiencing similar behaviour. Let's say I have a file called functions.ts which contains some functions that get data from a DB using Drizzle. If I add a
createServerFn()in that same file, I get thenode:async_hookserror. Moving thecreateServerFn()to a new file (or the route file) makes it work as noted earlier in the thread.Example:
schiller-manuel commentedon Jan 3, 2025
does this still occur if you don't export getEntriesCount?
leonlarsson commentedon Jan 3, 2025
Removing the exports makes it happier. If the file only exports a createServerFn, it has no more complaints
schiller-manuel commentedon Jan 3, 2025
dead code elimination will preserve all exports as you could be importing this from another file.
graup commentedon Feb 18, 2025
I also ran into this because I accidentally used a function from
@tanstack/start/serverin the client() part of a middleware. The build errored with a very unhelpful message,"Readable" is not exported by "__vite-browser-external", with no reference to the offending file. The annoying part is that it works in local dev, so you only notice this bug later when you might already have forgotten about where it might be from. Maybe we could improve the DX here a bit.WellDone2094 commentedon Mar 21, 2025
i'm encountering the same issue but i'm not sure what is generating it
yarabramasta commentedon Mar 28, 2025
+1
i got this kind of error from this path
node_modules/.pnpm/@[email protected]/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js:2:910 remaining items
jmdfm commentedon Apr 25, 2025
Thanks @Necmttn! 🥇
I had to use
createIsomorphicFnalso, because in myCSRFmiddleware, it was pulling in a function which usednode:cryptoand was getting added to the client bundle:OttersProduction commentedon May 4, 2025
Having a similar issue, I even refactored to have the code where the only server code in src is in utils and middleware, drizzle moved to outside of src but still having this issue.
cant figure where or what is importing server code inside client code, the only reference i got to Readable is in s3 implementation that is only in utils and imported into a createServerFn.
Running in dev works just fine no errors not runtime crashes.
Libraries that might use both server and client that i use are, React Query, better-auth.
Also my app.config
abuuzayr commentedon May 12, 2025
@OttersProduction Try adding this to your
viteblock:so the resulting config looks like
xuxucode commentedon Jul 3, 2025
As of TanStack Start v1.121.0, create the
src/server.tsserver entry file and attach needed methods to theglobalThisobject:Then use it in the server context:
mackattack3k commentedon Jul 4, 2025
I had the same AsyncLocalStorage issue in a Tanstack Start + Clerk basic starter without any middleware like so:
Solution
The solution was to put the getAuth + getWebRequest in a separate
createServerFnand then it worked. No config changes needed.otherFile.tsindex.tsxI guess in hindsight it might be obvious that when wrapping with a serverFn it works 🤷
qcho commentedon Jul 16, 2025
Have anyone found a quick way to troubleshoot what code is actually exposing things to the client?
I would love to be able to render the vite module graph somehow but it seems every visualizer depends on build passing.
AtAFork commentedon Aug 6, 2025
agreed with @qcho that would be really helpful if possible. Also for anyone else that comes across any bug with AsyncLocalStorage, It could be a sign that calling a
serverOnlyfunction on the front end somewhere, and I've also had the error pop-up from updating tanstack packages (even without changes to my codebase) and then solved by a simplerm -rf node_modules/ package-lock.jsonand reinstall.Trombecher commentedon Oct 21, 2025
Encountering the issue when scaffolding a SolidJS app with
Even when deleting all server fns and middleware (thus only importing from "@tanstack/solid-router" and "@tanstack/solid-router-devtools"), I still get the error:
kalebmmm commentedon Oct 24, 2025
I ran into the same
externalized for browser compatibilityissue as well. In our case, using better-auth, we accidentally added thereactStartCookiesplugin (a server plugin) increateAuthClient. Removing that did the trick.andybons commentedon Nov 4, 2025
@qcho @AtAFork I had success with examining the network panel of Chrome DevTools while in dev mode. Each file has an initiator that can be traced back to the file that imported it. That helped me narrow down what was importing server-only code.
niklasp commentedon Feb 18, 2026
what is the recommended way of addressing this?
ilkergzlkkr commentedon Feb 18, 2026
try to do an
export defaultwith separate file just like this: #2783 (comment)works for me
schiller-manuel commentedon Feb 19, 2026
wit our new import protection feature the detection of such issues should be solved: https://tanstack.com/start/v0/docs/framework/react/guide/import-protection
if you still encounter problems, please create new github issues including a complete minimal reproducer
chore(deps): upgrade vite 8, nitro 3 stable, tailwind 4.2.4 (#266)