Skip to content

v1.132.2 Rollup failed to resolve import "tanstack-start-injected-head-scripts:v" #5196

Closed

Description

@frixou89

Which project does this relate to?

Start

Describe the bug

Error during build on version 1.132.2.

error during build:
[vite]: Rollup failed to resolve import "tanstack-start-injected-head-scripts:v" from /node_modules/@tanstack/start-server-core/dist/esm/loadVirtualModule.js".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
    at viteLog (file://node_modules/vite/dist/node/chunks/dep-D5b0Zz6C.js:33954:57)
    at file://node_modules/vite/dist/node/chunks/dep-D5b0Zz6C.js:33990:73
    at onwarn (file://node_modules/@vitejs/plugin-react/dist/index.js:55:7)
    at file://node_modules/vite/dist/node/chunks/dep-D5b0Zz6C.js:33990:28
    at onRollupLog (file://node_modules/vite/dist/node/chunks/dep-D5b0Zz6C.js:33985:63)
    at onLog (file://node_modules/vite/dist/node/chunks/dep-D5b0Zz6C.js:33786:4)
    at file://node_modules/rollup/dist/es/shared/node-entry.js:20936:32
    at Object.logger [as onLog] (file://node_modules/rollup/dist/es/shared/node-entry.js:22822:9)
    at ModuleLoader.handleInvalidResolvedId (file://node_modules/rollup/dist/es/shared/node-entry.js:21566:26)
    at ModuleLoader.resolveDynamicImport (file://node_modules/rollup/dist/es/shared/node-entry.js:21624:58)

[vite] (client) Pre-transform error: Failed to resolve import "tanstack-start-injected-head-scripts:v" from "../../node_modules/@tanstack/start-server-core/dist/esm/loadVirtualModule.js?v=7e60bb72". Does the file exist?
  Plugin: vite:import-analysis
  File: /home/frixou89/projects/fitable-trpc/node_modules/@tanstack/start-server-core/dist/esm/loadVirtualModule.js?v=7e60bb72:17:27
  7  |        return await import("tanstack-start-server-fn-manifest:v");
  8  |      case VIRTUAL_MODULES.injectedHeadScripts:
  9  |        return await import("tanstack-start-injected-head-scripts:v");
     |                            ^
  10 |      default:
  11 |        throw new Error(`Unknown virtual module: ${id}`); (x2)

Your Example Website or App

N/A

Steps to Reproduce the Bug or Issue

__root.tsx

function RootComponent() {
  const { locale } = Route.useRouteContext();

  return (
      <RootDocument locale={locale}>
        <Outlet />
      </RootDocument>
  );
}

---
function RootDocument({
  children,
  locale,
}: Readonly<{ children: ReactNode; locale: string }>) {
  return (
    <html className="h-full" lang={locale}>
      <head>
        <HeadContent />
      </head>
      <body className="h-full">
        {children}
        <ReactQueryDevtools position="bottom" buttonPosition="bottom-right" />
        <Scripts />
      </body>
    </html>
  );
}

router.tsx

export function getRouter() {
  const router = createTanStackRouter({
    routeTree: routeTree,
    scrollRestoration: true,
    defaultPreloadStaleTime: 0,
    context: {
      queryClient,
      session: null,
    },
    defaultNotFoundComponent: () => <PageNotFound />,
    defaultErrorComponent: (props) => <PageError {...props} />,
    Wrap: ({ children }) => (
      <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
    ),
  });

  return router;
}

Expected behavior

Should work as described in docs and starter app.

If I remove <Scripts /> from the RootDocument component then I get no errors on development but I do on vite build.

Screenshots or Videos

No response

Platform

  • Router / Start Version: 1.132.2
  • OS: Windows (WSL)
  • Browser: Chrome
  • Bundler: vite
  • Bundler Version: 7.1.6

Additional context

No response

Activity

  1. MGSimard commented on Sep 24, 2025

    @MGSimard

    Also dumpstered my static prerendering builds and public folder file references, rolled back to v1.131.50 and it returned to normal.

  2. schiller-manuel commented on Sep 24, 2025

    @schiller-manuel
    Collaborator

    can you please provide a complete reproducer project for this?

  3. mrhut10 commented on Sep 24, 2025

    @mrhut10

    yep I'm seeing the same thing on a project i'm attempting to upgrade into that version.
    I've parked the upgrade for now

  4. frixou89 commented on Sep 24, 2025

    @frixou89
    Author

    can you please provide a complete reproducer project for this?

    Managed to reproduce check it here stackblitz

    The problem occurs when I import import { getRequest } from "@tanstack/react-start/server"; anywhere

  5. supersnager commented on Sep 24, 2025

    @supersnager

    When I run vite dev, I see multiple similar errors in the console.

    ✘ [ERROR] Could not resolve "tanstack-start-manifest:v"
    
        node_modules/@tanstack/start-server-core/dist/esm/loadVirtualModule.js:5:26:
          5 │       return await import("tanstack-start-manifest:v");
            ╵                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ✘ [ERROR] Could not resolve "#tanstack-router-entry"
    
        node_modules/@tanstack/start-server-core/dist/esm/createStartHandler.js:40:33:
          40 │       routerEntry = await import("#tanstack-router-entry");
             ╵                                  ~~~~~~~~~~~~~~~~~~~~~~~~
    ✘ [ERROR] Could not resolve "#tanstack-start-entry"
    
        node_modules/@tanstack/start-server-core/dist/esm/createStartHandler.js:43:32:
          43 │       startEntry = await import("#tanstack-start-entry");
             ╵                                 ~~~~~~~~~~~~~~~~~~~~~~~
    ✘ [ERROR] Could not resolve "tanstack-start-server-fn-manifest:v"
    
        node_modules/@tanstack/start-server-core/dist/esm/loadVirtualModule.js:7:26:
          7 │       return await import("tanstack-start-server-fn-manifest:v");
            ╵                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ✘ [ERROR] Could not resolve "tanstack-start-injected-head-scripts:v"
    
        node_modules/@tanstack/start-server-core/dist/esm/loadVirtualModule.js:9:26:
          9 │       return await import("tanstack-start-injected-head-scripts:v");
            ╵                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ✘ [ERROR] Could not resolve "#tanstack-router-entry"
    
        node_modules/@tanstack/start-server-core/dist/esm/createStartHandler.js:40:33:
          40 │       routerEntry = await import("#tanstack-router-entry");
             ╵                                  ~~~~~~~~~~~~~~~~~~~~~~~~
    ✘ [ERROR] Could not resolve "#tanstack-start-entry"
    
        node_modules/@tanstack/start-server-core/dist/esm/createStartHandler.js:43:32:
          43 │       startEntry = await import("#tanstack-start-entry");
             ╵                                 ~~~~~~~~~~~~~~~~~~~~~~~
    
    
  6. schiller-manuel commented on Sep 24, 2025

    @schiller-manuel
    Collaborator

    @frixou89 you are importing a server only function inside __root
    this will not be compiled away by Start as you dont reference it inside e.g. a server function handler.

  7. moncapitaine commented on Sep 24, 2025

    @moncapitaine

    I am on upgrading my project from a very early tanstack start version to the latest one and get a similar error running vite dev. I already downgraded to 1.132.0 to see if it breaks as well and yes, it does.

    Not sure if it makes any difference, but my project is running inside dev-containers, so I need to use:

    "dev": "vite dev --port 3001 --host",
    

    Here is my console log:

    5:52:34 PM [vite] Internal server error: Failed to resolve import "tanstack-start-injected-head-scripts:v" from "../../node_modules/.pnpm/@tanstack+start-server-core@1.132.0_crossws@0.3.5/node_modules/@tanstack/start-server-core/dist/esm/loadVirtualModule.js?v=c8ada891". Does the file exist?
    @george-ai/chat-web:dev:   Plugin: vite:import-analysis
    @george-ai/chat-web:dev:   File: /workspaces/george-ai/node_modules/.pnpm/@tanstack+start-server-core@1.132.0_crossws@0.3.5/node_modules/@tanstack/start-server-core/dist/esm/loadVirtualModule.js?v=c8ada891:17:27
    @george-ai/chat-web:dev:   7  |        return await import("tanstack-start-server-fn-manifest:v");
    @george-ai/chat-web:dev:   8  |      case VIRTUAL_MODULES.injectedHeadScripts:
    @george-ai/chat-web:dev:   9  |        return await import("tanstack-start-injected-head-scripts:v");
    @george-ai/chat-web:dev:      |                            ^
    @george-ai/chat-web:dev:   10 |      default:
    @george-ai/chat-web:dev:   11 |        throw new Error(`Unknown virtual module: ${id}`);
    @george-ai/chat-web:dev:       at TransformPluginContext._formatLog (file:///workspaces/george-ai/node_modules/.pnpm/vite@6.3.6_@types+node@22.18.6_jiti@2.6.0_lightningcss@1.30.1_terser@5.44.0_tsx@4.20.5_yaml@2.8.1/node_modules/vite/dist/node/chunks/dep-Bu492Fnd.js:42517:41)
    @george-ai/chat-web:dev:       at TransformPluginContext.error (file:///workspaces/george-ai/node_modules/.pnpm/vite@6.3.6_@types+node@22.18.6_jiti@2.6.0_lightningcss@1.30.1_terser@5.44.0_tsx@4.20.5_yaml@2.8.1/node_modules/vite/dist/node/chunks/dep-Bu492Fnd.js:42514:16)
    @george-ai/chat-web:dev:       at normalizeUrl (file:///workspaces/george-ai/node_modules/.pnpm/vite@6.3.6_@types+node@22.18.6_jiti@2.6.0_lightningcss@1.30.1_terser@5.44.0_tsx@4.20.5_yaml@2.8.1/node_modules/vite/dist/node/chunks/dep-Bu492Fnd.js:40493:23)
    @george-ai/chat-web:dev:       at async file:///workspaces/george-ai/node_modules/.pnpm/vite@6.3.6_@types+node@22.18.6_jiti@2.6.0_lightningcss@1.30.1_terser@5.44.0_tsx@4.20.5_yaml@2.8.1/node_modules/vite/dist/node/chunks/dep-Bu492Fnd.js:40612:37
    @george-ai/chat-web:dev:       at async Promise.all (index 3)
    @george-ai/chat-web:dev:       at async TransformPluginContext.transform (file:///workspaces/george-ai/node_modules/.pnpm/vite@6.3.6_@types+node@22.18.6_jiti@2.6.0_lightningcss@1.30.1_terser@5.44.0_tsx@4.20.5_yaml@2.8.1/node_modules/vite/dist/node/chunks/dep-Bu492Fnd.js:40539:7)
    @george-ai/chat-web:dev:       at async EnvironmentPluginContainer.transform (file:///workspaces/george-ai/node_modules/.pnpm/vite@6.3.6_@types+node@22.18.6_jiti@2.6.0_lightningcss@1.30.1_terser@5.44.0_tsx@4.20.5_yaml@2.8.1/node_modules/vite/dist/node/chunks/dep-Bu492Fnd.js:42312:18)
    @george-ai/chat-web:dev:       at async loadAndTransform (file:///workspaces/george-ai/node_modules/.pnpm/vite@6.3.6_@types+node@22.18.6_jiti@2.6.0_lightningcss@1.30.1_terser@5.44.0_tsx@4.20.5_yaml@2.8.1/node_modules/vite/dist/node/chunks/dep-Bu492Fnd.js:35738:27)
    @george-ai/chat-web:dev:       at async viteTransformMiddleware (file:///workspaces/george-ai/node_modules/.pnpm/vite@6.3.6_@types+node@22.18.6_jiti@2.6.0_lightningcss@1.30.1_terser@5.44.0_tsx@4.20.5_yaml@2.8.1/node_modules/vite/dist/node/chunks/dep-Bu492Fnd.js:37253:24) (x2)
    
  8. frixou89 commented on Sep 24, 2025

    @frixou89
    Author

    @frixou89 you are importing a server only function inside __root this will not be compiled away by Start as you dont reference it inside e.g. a server function handler.

    I do call some server functions from __root.tsx for authentication very similar to the example shown here https://tanstack.com/start/latest/docs/framework/react/examples/start-basic-auth

    This used to work in previous version. Are you saying we can't call server functions from _root.tsx or beforeLoad hook anymore?

  9. schiller-manuel commented on Sep 24, 2025

    @schiller-manuel
    Collaborator

    no. i am saying you are importing a server only function from @tanstack/react-start/server which won't get compiled out for the client build.
    a server function, i.e. one created using createServerFn is of course ok

  10. zenios commented on Sep 24, 2025

    @zenios
    Contributor

    If the server function utilizes a middleware that imports server only types such as

    const tokenStorage = new AsyncLocalStorage();

    Then the build fails with the messages above.

    Prior to rc we used to set/get Context i assume know we have to do it with AsyncLocalStorage

  11. jrnxf commented on Sep 24, 2025

    @jrnxf

    In my case I was using serverOnly which, though still mentioned in the docs, seems to have been replaced with createServerOnlyFn. Changing this fixed the error for me

  12. moncapitaine commented on Sep 25, 2025

    @moncapitaine

    In my case I was using serverOnly which, though still mentioned in the docs, seems to have been replaced with createServerOnlyFn. Changing this fixed the error for me

    Same for me. I used a exported function for usage inside server functions only. These kind of functions need to be createServerOnlyFn to avoid that they are included in the client package. Thx!

  13. supersnager commented on Sep 25, 2025

    @supersnager

    @schiller-manuel Thank you for the explanation. In my case it was:

    // src/__root.tsx
    import {getCookie} from "@tanstack/react-start-server";

    I have another question: Is it a good practice to use getCookie function from this package?
    I'm asking because the package's description says:
    This package is not meant to be used directly. It is a dependency of @tanstack/react-start
    If not, what is the recommended way to get a cookie from the request in SSR?

  14. np-13 commented on Sep 25, 2025

    @np-13
    Contributor

    To reproduce, the following snippet should be added anywhere in the code:

    import { getRequestUrl } from "@tanstack/react-start/server";
    
    function unusedFunction() {
      return getRequestUrl();
    }

    Codesandbox: https://codesandbox.io/p/devbox/dead-code-elimitation-repro-hxnjh2

  15. frixou89 commented on Sep 25, 2025

    @frixou89
    Author

    To reproduce, the following snippet should be added anywhere in the code:

    import { getRequestUrl } from "@tanstack/react-start/server";

    function unusedFunction() {
    return getRequestUrl();
    }
    Codesandbox: https://codesandbox.io/p/devbox/dead-code-elimitation-repro-hxnjh2

    Exactly. Is that a bug though or something we should avoid doing and if so, what is the recommended approach when we want to access the request/cookies in a server function?

  16. 29 remaining items

  17. schiller-manuel commented on Oct 11, 2025

    @schiller-manuel
    Collaborator

    @xuxucode why would this be necessary?

  18. xuxucode commented on Oct 11, 2025

    @xuxucode

    Because in this way, server functions are only exposed in server context, avoid leaking them in client context.

  19. schiller-manuel commented on Oct 12, 2025

    @schiller-manuel
    Collaborator

    this shouldnt be necessary. when do you think you need this? can you please provide a complete example where this helps?

  20. xuxucode commented on Oct 12, 2025

    @xuxucode

    I created a repo at https://github.com/xuxucode/tanstack-react-start-ssr based on the router/examples/react/start-basic example. All necessary changes are within commit c03abf0

  21. schiller-manuel commented on Oct 12, 2025

    @schiller-manuel
    Collaborator

    @xuxucode you are just doing manually what createIsomorphicFn() gives you. this is not related to the original issue, you were actually calling a server only function in a place that expects isomorphic functions (loader)

  22. xuxucode commented on Oct 12, 2025

    @xuxucode

    Thanks, createIsomorphicFn works.

  23. schiller-manuel commented on Oct 13, 2025

    @schiller-manuel
    Collaborator

    i am closing this now since this is not a bug but was caused by incorrect usage. if anyone encounters a similar issue that is not resolved by following the hints above, then please create a new github issue including a complete minimal reproducer

  24. lino-levan commented on Oct 13, 2025

    @lino-levan

    Hey @schiller-manuel, I think this issue being open is valuable especially since the error message is so obtuse. We're slowly migrating our app to the tanstack start RC but we're hitting roughly ~10 of these errors throughout our codebase and it's incredibly painful. I would absolutely love to see work towards "hey this file right here is the source of the issues, you can't do that" vs "you messed up, no I'm not going to tell you where". Happy to open another issue to get a better error message here if that's what you'd prefer.

  25. schiller-manuel commented on Oct 13, 2025

    @schiller-manuel
    Collaborator

    @lino-levan yes please open a new issue for that. we are working on that btw, but tracking this in an issue is good

  26. mike-littlechapter commented on Nov 18, 2025

    @mike-littlechapter

    I believe this is definitely a bug.

    I have file with a single export: a serverFn created using createServerFn({..})

    this server function uses getRequestHeader() from '@tanstack/react-start/server' to get the origin header.

    it is called in an onClick handler on a button in the app, not even in a loader fn.

    using getRequestHeader makes the app un-buildable and the dev server un-runnable.

    removing the import of getRequestHeader and not using it fixes everything.

    If this isnt a bug, then it would be nice if the "server functions" could be annotated and documented that they are not able to be used within "serverFunctions" (the ones we make using createServerFn)

    using a dynamic import within the createServerFn body was not able to fix the issue.

    Its think its almost certainly a bug as other server functions within my app are able to use these utilities fine

    please re-open this issue.

    EDIT:

    wrapping the server utility functions in createServerOnlyFn() before calling it within the serverFn resolved the issue

    eg

    const getRequestHeaderSvOnly = createServerOnlyFn((headerName: string): string | undefined => {
      return getRequestHeader(headerName);
    });
    
    
    
    export const myServerFn = createServerFn({
      method: 'POST',
    })
      .inputValidator(schema)
      .middleware([authentication])
      .handler<Promise<any>>(async ({ data, context }) => {
    
        const origin = getRequestHeaderSvOnly('origin') || 'foobar';
    //rest
    
    });
  27. mike-littlechapter commented on Nov 18, 2025

    @mike-littlechapter

    For anyone landing here please see #5892 for the exact cause of my woes. it may be whats causing your problems if none of the above solutions worked

  28. omergulcicek commented on Dec 24, 2025

    @omergulcicek

    Solution 1: Move Server Functions to Separate Files (Recommended)

    After further investigation, the most robust solution is to move your Server Functions into separate files. The "Rollup failed to resolve" error occurs because Vite attempts to bundle server-only utilities (like getCookies, getRequestUrl, or database clients) into the client-side bundle. When a createServerFn is defined within the same file as a Client Component, Vite sometimes struggles to tree-shake the server-only dependencies, leading to the virtual module resolution error.

    The Fix

    By moving the Server Function definition to a dedicated .ts file, you create a clear boundary between server-side logic and client-side UI.

    1. Define the Server Function (login.ts): Keep all server-side logic and heavy imports (like Supabase, DB clients, or Node.js built-ins) here.

    // login.ts
    import { createServerFn } from '@tanstack/react-start'
    import { getSupabaseServerClient } from '@/lib/supabase/server' 
    
    export const login = createServerFn({ method: 'POST' })
      .handler(async ({ data }) => {
        const supabase = getSupabaseServerClient()
        // ... server-side logic
        return { ok: true }
      })

    2. Import in your Component (LoginPage.tsx): Import the function as a clean reference. Vite will now correctly handle this as a remote call rather than trying to bundle the server code.

    // LoginPage.tsx
    import { login } from './login'
    
    function LoginPage() {
      const handleSubmit = async (e) => {
        // ...
        await login({ data: { email, password } })
      }
      // ...
    }

    This approach is architecturally cleaner and prevents the build process from leaking server-only modules into the client bundle. If you are unable to move your functions for some reason, you can still use the Dynamic Import method mentioned below as a fallback.

    Solution 2: Use Dynamic Imports (Alternative/Fallback)

    The issue is caused by static imports of server-side utilities -such as getRequestUrl, getCookies, and setCookie- at the top level of your files. During the build process, Vite attempts to include these in the client bundle, which triggers the virtual module resolution error because these modules are designed to run only in a Node.js/server environment.

    The Fix

    To resolve this, move these imports inside the server function scope using dynamic imports (await import()). Bu doing so, you prevent Vite from bundling these server-only dependencies into the client-side code.

    Example

    ❌ Before (Static Import):

    import { getRequestUrl } from "@tanstack/react-start/server"; // Causes build error
    
    const authCallbackFn = createServerFn({ method: "GET" }).handler(async () => {
      const requestUrl = getRequestUrl();
    });

    ✅ After (Dynamic Import):

    const authCallbackFn = createServerFn({ method: "GET" }).handler(async () => {
      // Imported only when the function runs on the server
      const { getRequestUrl } = await import("@tanstack/react-start/server"); 
      const requestUrl = getRequestUrl();
    });

    Note: Apply this same logic to getCookies and setCookie within your handlers to ensure complete compatibility.

  29. bilalesi commented on Dec 27, 2025

    @bilalesi

    const { getRequestUrl } = await import("@tanstack/react-start/server");

    this works @omergulcicek, thanks!

  30. omergulcicek commented on Feb 3, 2026

    @omergulcicek

    I’ve encountered the same issue and done a deep dive into why this happens. It usually stems from the server/client boundary being blurred (e.g., importing server-only utilities like Supabase or DB clients into files that end up in the client bundle).

    I wrote a detailed guide on how to resolve this by properly separating your server logic and using createServerFn correctly to avoid these virtual module resolution errors.

    You can check out the solution here: TanStack Start: Resolving the tanstack-start-injected-head-scripts Error

    Hope it helps anyone else stuck on this!

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions