Skip to content

Start - Server Function Middleware Included in Client Bundle #2783

Closed

Description

@scrawfor

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

StackBlitz Reproduction Link

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

  1. added
    start
    on Nov 16, 2024
  2. SeanCassiere commented on Nov 16, 2024

    @SeanCassiere
    Member

    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.

    async function abstractedFunction() {
    console.info('Fetching posts...');
    await new Promise(r => setTimeout(r, 500));
    return axios.get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10));
    }
    function zodValidator<TSchema extends z.ZodSchema, TResult>(schema: TSchema, fn: (input: z.output<TSchema>) => TResult) {
    return async (input: unknown) => {
    return fn(schema.parse(input));
    };
    }

  3. dotnize commented on Nov 17, 2024

    @dotnize
    Contributor

    What worked for me was moving the middleware definition (createMiddleware) into its own separate file

  4. SeanCassiere commented on Nov 18, 2024

    @SeanCassiere
    Member

    I'm having difficult reproducing this using our "start-supabase-basic" example.

    import * as React from 'react'
    import { createFileRoute } from '@tanstack/react-router'
    import { createMiddleware, createServerFn, useServerFn } from '@tanstack/start'
    import { getSupabaseServerClient } from '~/utils/supabase'
    
    const authMiddleware = createMiddleware().server(async ({ next }) => {
      const supa = getSupabaseServerClient()
      const user = await supa.auth.getUser()
      console.log('user response', user)
      return next({ context: { user } })
    })
    
    const checkAuthFn = createServerFn()
      .middleware([authMiddleware])
      .handler(({ context }) => {
        console.log('checkAuthFn', context.user)
        return { foo: 'bar' }
      })
    
    export const Route = createFileRoute('/test')({
      component: RouteComponent,
    })
    
    function RouteComponent() {
      const fn = useServerFn(checkAuthFn)
    
      return (
        <div className="flex gap-2">
          <button
            onClick={() => {
              checkAuthFn().then((res) => {
                console.log(Date.now(), 'direct', res)
              })
            }}
          >
            Test Direct
          </button>
          <button
            onClick={() => {
              fn().then((res) => {
                console.log(Date.now(), 'useServerFn', res)
              })
            }}
          >
            Test useServerFn
          </button>
        </div>
      )
    }
  5. scrawfor commented on Nov 18, 2024

    @scrawfor
    Author

    @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.

    I'm having difficult reproducing this using our "start-supabase-basic" example.

  6. scrawfor commented on Nov 18, 2024

    @scrawfor
    Author

    @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.ts creates a supbase client and an authMiddleware. 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]) from app/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 same dbMilddleware code is instead defined in app/routes/index this doesn't break.

  7. dan-gamble commented on Dec 5, 2024

    @dan-gamble

    What worked for me was moving the middleware definition (createMiddleware) into its own separate file

    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 getEvent in the shopNameSchema. I imagine this is finding it's way into a client package somehow

    __root.tsx

    const authenticateUser = createServerFn({ method: "GET" })
      .middleware([validateSearchParamsMiddleware])
      .handler(async () => {
        return {
          name: "Dan"
        }
      })
    
    export const Route = createRootRoute({
      head: () => ({
        meta: [
          {
            charSet: 'utf-8',
          },
          {
            name: 'viewport',
            content: 'width=device-width, initial-scale=1',
          },
          {
            title: 'TanStack Start Starter',
          },
        ],
      }),
      component: RootComponent,
      async beforeLoad () {
        const user = await authenticateUser()
    
        if (!user) {
          throw new Error("Unauthenticated")
        }
      }
    })

    app/middleware/shopify/validate-search-params-middleware.tsx

    import { createMiddleware } from "@tanstack/start";
    import { getEvent, getValidatedQuery } from "vinxi/http";
    import { z } from "zod";
    
    export const shopNameSchema = z.string().transform(shop => {
      const event = getEvent();
    
      return event.context.shopify.utils.sanitizeShop(shop);
    });
    
    export const shopifySearchParamsSchema = z.object({
      embedded: z.enum(["0", "1"]),
      hmac: z.string(),
      host: z.string(),
      id_token: z.string(),
      locale: z.string(),
      session: z.string(),
      shop: shopNameSchema,
      timestamp: z.string(),
    });
    
    export const validateSearchParamsMiddleware = createMiddleware()
      .server(async ({ next }) => {
        const event = getEvent()
    
        const validatedQuery = await getValidatedQuery(event, async query => {
          return shopifySearchParamsSchema.safeParse(query)
        });
    
        if (validatedQuery.success) {
          return next({
            context: {
              query: validatedQuery.data
            }
          });
        }
    
        throw new Error("Unable to parse search params")
      })

    Image

  8. JohnnyCrazy commented on Dec 26, 2024

    @JohnnyCrazy

    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]) from app/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 same dbMilddleware code is instead defined in app/routes/index this doesn't break.

    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:

    async function requireUserOnServer() {
      const session = await useAppSession();
      // load user from db with supabase/db client and return it
    }
    
    const requireUserMiddleware = createMiddleware().server(async ({ next }) => {
      const user = await requireUserOnServer();
      return next({ context: { user } });
    });

    but this doesn't:

    // notice the `export`
    export async function requireUserOnServer() {
      const session = await useAppSession();
      // load user from db with supabase/db client and return it
    }
    
    const requireUserMiddleware = createMiddleware().server(async ({ next }) => {
      const user = await requireUserOnServer();
      return next({ context: { user } });
    });

    Can create a minimal example if needed

  9. leonlarsson commented on Jan 3, 2025

    @leonlarsson

    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 the node:async_hooks error. Moving the createServerFn() to a new file (or the route file) makes it work as noted earlier in the thread.

    Example:

    // functions.ts - causes node:async_hooks error
    export const getGuestbookEntriesServerFn = createServerFn()
      .validator((data: { namedEntriesOnly: boolean }) => data)
      .handler(async (ctx) => {
        const [entriesCount] = await Promise.all([
          getEntriesCount(ctx.data.namedEntriesOnly),
        ]);
    
        return {
          entriesCount,
        };
      });
    
    export const getEntriesCount = async (namedEntriesOnly: boolean): Promise<number> => {
      const db = await getDb();
      try {
        const result = await db.$count(entries, namedEntriesOnly ? isNotNull(entries.name) : undefined);
        return result;
      } catch (error) {
        console.log(error);
        return 0;
      }
    };
  10. schiller-manuel commented on Jan 3, 2025

    @schiller-manuel
    Collaborator

    does this still occur if you don't export getEntriesCount?

  11. leonlarsson commented on Jan 3, 2025

    @leonlarsson

    does this still occur if you don't export getEntriesCount?

    Removing the exports makes it happier. If the file only exports a createServerFn, it has no more complaints

  12. schiller-manuel commented on Jan 3, 2025

    @schiller-manuel
    Collaborator

    dead code elimination will preserve all exports as you could be importing this from another file.

  13. graup commented on Feb 18, 2025

    @graup
    Contributor

    I also ran into this because I accidentally used a function from @tanstack/start/server in 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.

  14. WellDone2094 commented on Mar 21, 2025

    @WellDone2094

    i'm encountering the same issue but i'm not sure what is generating it

    [plugin vite:resolve] Module "node:fs" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-client-core/dist/esm/createServerFn.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:path" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-client-core/dist/esm/createServerFn.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:fs" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-client-core/dist/esm/createServerFn.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:path" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-client-core/dist/esm/createServerFn.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:stream" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/react-start-server/dist/esm/defaultStreamHandler.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:stream/web" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:stream" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:async_hooks" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/h3.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    ✓ 1987 modules transformed.
    ✗ Build failed in 1.23s
    
    [6:26:58 PM]  ERROR  node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js (2:9): "Readable" is not exported by "__vite-browser-external", imported by "node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js".
    file: /Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js:2:9
    
    1: import { ReadableStream } from "node:stream/web";
    2: import { Readable } from "node:stream";
                ^
    3: import { createControlledPromise } from "@tanstack/router-core";
    4: function transformReadableStreamWithRouter(router, routerStream) {
    
    
        at getRollupError (node_modules/rollup/dist/es/shared/parseAst.js:397:41)
        at error (node_modules/rollup/dist/es/shared/parseAst.js:393:42)
        at Module.error (node_modules/rollup/dist/es/shared/node-entry.js:16700:16)
        at Module.traceVariable (node_modules/rollup/dist/es/shared/node-entry.js:17149:29)
        at ModuleScope.findVariable (node_modules/rollup/dist/es/shared/node-entry.js:14805:39)
        at FunctionScope.findVariable (node_modules/rollup/dist/es/shared/node-entry.js:5582:38)
        at FunctionBodyScope.findVariable (node_modules/rollup/dist/es/shared/node-entry.js:5582:38)
        at MemberExpression.bind (node_modules/rollup/dist/es/shared/node-entry.js:7285:49)
        at CallExpression.bind (node_modules/rollup/dist/es/shared/node-entry.js:2783:23)
        at CallExpression.bind (node_modules/rollup/dist/es/shared/node-entry.js:11928:15)
    
    
    
    [6:26:58 PM]  ERROR  node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js (2:9): "Readable" is not exported by "__vite-browser-external", imported by "node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js".
    file: /Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js:2:9
    
    1: import { ReadableStream } from "node:stream/web";
    2: import { Readable } from "node:stream";
                ^
    3: import { createControlledPromise } from "@tanstack/router-core";
    4: function transformReadableStreamWithRouter(router, routerStream) {
    
    
    
     ERROR  Exited with code: 1                                                                                                                                                                                                           6:26:58 PM
    
        at CommandChild.pipedStdoutBuffer (node_modules/dax-sh/esm/mod.js:9392:19)
        at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    
    
    
     ERROR  Exited with code: 1```
    
  15. yarabramasta commented on Mar 28, 2025

    @yarabramasta

    i'm encountering the same issue but i'm not sure what is generating it

    [plugin vite:resolve] Module "node:fs" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-client-core/dist/esm/createServerFn.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:path" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-client-core/dist/esm/createServerFn.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:fs" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-client-core/dist/esm/createServerFn.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:path" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-client-core/dist/esm/createServerFn.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:stream" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/react-start-server/dist/esm/defaultStreamHandler.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:stream/web" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:stream" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    [plugin vite:resolve] Module "node:async_hooks" has been externalized for browser compatibility, imported by "/Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/h3.js". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
    ✓ 1987 modules transformed.
    ✗ Build failed in 1.23s
    
    [6:26:58 PM]  ERROR  node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js (2:9): "Readable" is not exported by "__vite-browser-external", imported by "node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js".
    file: /Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js:2:9
    
    1: import { ReadableStream } from "node:stream/web";
    2: import { Readable } from "node:stream";
                ^
    3: import { createControlledPromise } from "@tanstack/router-core";
    4: function transformReadableStreamWithRouter(router, routerStream) {
    
    
        at getRollupError (node_modules/rollup/dist/es/shared/parseAst.js:397:41)
        at error (node_modules/rollup/dist/es/shared/parseAst.js:393:42)
        at Module.error (node_modules/rollup/dist/es/shared/node-entry.js:16700:16)
        at Module.traceVariable (node_modules/rollup/dist/es/shared/node-entry.js:17149:29)
        at ModuleScope.findVariable (node_modules/rollup/dist/es/shared/node-entry.js:14805:39)
        at FunctionScope.findVariable (node_modules/rollup/dist/es/shared/node-entry.js:5582:38)
        at FunctionBodyScope.findVariable (node_modules/rollup/dist/es/shared/node-entry.js:5582:38)
        at MemberExpression.bind (node_modules/rollup/dist/es/shared/node-entry.js:7285:49)
        at CallExpression.bind (node_modules/rollup/dist/es/shared/node-entry.js:2783:23)
        at CallExpression.bind (node_modules/rollup/dist/es/shared/node-entry.js:11928:15)
    
    
    
    [6:26:58 PM]  ERROR  node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js (2:9): "Readable" is not exported by "__vite-browser-external", imported by "node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js".
    file: /Users/andreabenfatti/Dev/tanstack-start/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js:2:9
    
    1: import { ReadableStream } from "node:stream/web";
    2: import { Readable } from "node:stream";
                ^
    3: import { createControlledPromise } from "@tanstack/router-core";
    4: function transformReadableStreamWithRouter(router, routerStream) {
    
    
    
     ERROR  Exited with code: 1                                                                                                                                                                                                           6:26:58 PM
    
        at CommandChild.pipedStdoutBuffer (node_modules/dax-sh/esm/mod.js:9392:19)
        at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    
    
    
     ERROR  Exited with code: 1```
    

    +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:9

  16. 10 remaining items

  17. jmdfm commented on Apr 25, 2025

    @jmdfm

    Thanks @Necmttn! 🥇

    I had to use createIsomorphicFn also, because in my CSRF middleware, it was pulling in a function which used node:crypto and was getting added to the client bundle:

    const generateCsrfTokenIso = createIsomorphicFn()
      .server(async () => {
        const { generateCsrfToken } = await import("@nanocanvas/system/encryption");
        return generateCsrfToken();
      })
      .client(async (): Promise<string> => {
        console.error("generateCsrfTokenIso called on client!");
        throw new Error("CSRF token generation cannot occur on the client.");
      });
  18. OttersProduction commented on May 4, 2025

    @OttersProduction

    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.

    [18:12:41]  ERROR  node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js (2:9): "Readable" is not exported by "__vite-browser-external", imported by "node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js".
    file: node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js:2:9
    
    1: import { ReadableStream } from "node:stream/web";
    2: import { Readable } from "node:stream";
                ^
    3: import { createControlledPromise } from "@tanstack/router-core";
    4: function transformReadableStreamWithRouter(router, routerStream) {
    
    

    Also my app.config

    import { defineConfig } from "@tanstack/react-start/config";
    import tsConfigPaths from "vite-tsconfig-paths";
    
    export default defineConfig({
      tsr: {
        appDirectory: "src",
      },
      server: {
        preset: "node-server",
      },
      vite: {
        plugins: [
          tsConfigPaths({
            projects: ["./tsconfig.json"],
          }),
        ],
      },
    });
  19. abuuzayr commented on May 12, 2025

    @abuuzayr

    @OttersProduction Try adding this to your vite block:

    build: {
      rollupOptions: {
        // Treat Node.js modules as external
        external: [
          'node:stream',
          'node:stream/web',
          'node:async_hooks',
          'node:fs',
          'node:path'
        ]
      }
    }

    so the resulting config looks like

    export default defineConfig({
      ...
      vite: {
        plugins: [
          ...
        ],
        build: {
          ...
          rollupOptions: {
            // Treat Node.js modules as external
            external: [
              'node:stream',
              'node:stream/web',
              'node:async_hooks',
              'node:fs',
              'node:path'
            ]
          }
        }
      },
    })
  20. xuxucode commented on Jul 3, 2025

    @xuxucode

    As of TanStack Start v1.121.0, create the src/server.ts server entry file and attach needed methods to the globalThis object:

    diff --git a/server.ts b/server.ts
    index dd3449b..266b1e9 100644
    --- a/server.ts
    +++ b/server.ts    
    @@ -1,9 +1,26 @@
     import {
       createStartHandler,
       defaultStreamHandler,
    +  getCookie,
    +  getHeader,
    +  getHeaders,
     } from '@tanstack/react-start/server'
     import { createRouter } from './router'
     
     export default createStartHandler({
       createRouter,
     })(defaultStreamHandler)
    +
    +globalThis.tanstackStartServer = {
    +  getHeader,
    +  getHeaders,
    +  getCookie,
    +}
    +
    +declare global {
    +  var tanstackStartServer: {
    +    getHeader: typeof getHeader
    +    getHeaders: typeof getHeaders
    +    getCookie: typeof getCookie
    +  }
    +}

    Then use it in the server context:

    if (typeof window === 'undefined') {
       const headers = globalThis.tanstackStartServer.getHeaders()
       return headers
    }
  21. mackattack3k commented on Jul 4, 2025

    @mackattack3k

    I had the same AsyncLocalStorage issue in a Tanstack Start + Clerk basic starter without any middleware like so:

    import {createFileRoute} from "@tanstack/react-router";
    import {getAuth} from "@clerk/tanstack-react-start/server";
    import { getWebRequest } from '@tanstack/react-start/server';
    
    export const Route = createFileRoute('/')({
        loader: async () => {
            const { userId } = await getAuth(getWebRequest());
            return {
                userId,
            };
        },
        component: Component,
    });
    
    function Component() {
        const { userId } = Route.useLoaderData();
        return <div>User ID: {userId}</div>;
    }

    Solution

    The solution was to put the getAuth + getWebRequest in a separate createServerFn and then it worked. No config changes needed.

    otherFile.ts

    import { getWebRequest } from '@tanstack/react-start/server';
    const getAuth = async () => {
        const { userId } = await getAuth(getWebRequest());
        return { userId };
    }

    index.tsx

    import {createFileRoute} from "@tanstack/react-router";
    import {getAuth} from "./otherFile.ts";
    
    export const Route = createFileRoute('/')({
        loader: async () => {
            const { userId } = await getAuth()
            return {
                userId,
            };
        },
        component: Component,
    });
    
    function Component() {
        const { userId } = Route.useLoaderData();
        return <div>User ID: {userId}</div>;
    }

    I guess in hindsight it might be obvious that when wrapping with a serverFn it works 🤷

  22. qcho commented on Jul 16, 2025

    @qcho

    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.

  23. AtAFork commented on Aug 6, 2025

    @AtAFork
    Contributor

    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 serverOnly function 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 simple rm -rf node_modules/ package-lock.json and reinstall.

  24. Trombecher commented on Oct 21, 2025

    @Trombecher

    Encountering the issue when scaffolding a SolidJS app with

    bun create @tanstack/start@latest --framework solid
    

    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:

    Uncaught (in promise) TypeError: import_node_async_hooks.AsyncLocalStorage is not a constructor
    
  25. kalebmmm commented on Oct 24, 2025

    @kalebmmm

    I ran into the same externalized for browser compatibility issue as well. In our case, using better-auth, we accidentally added the reactStartCookies plugin (a server plugin) in createAuthClient. Removing that did the trick.

  26. andybons commented on Nov 4, 2025

    @andybons

    @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.

  27. niklasp commented on Feb 18, 2026

    @niklasp

    what is the recommended way of addressing this?

  28. ilkergzlkkr commented on Feb 18, 2026

    @ilkergzlkkr

    try to do an export default with separate file just like this: #2783 (comment)

    works for me

  29. schiller-manuel commented on Feb 19, 2026

    @schiller-manuel
    Collaborator

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    revisit-after-devinxistart

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions