router icon indicating copy to clipboard operation
router copied to clipboard

Build hangs after prerender: SSR timeouts in transformStreamWithRouter are never cleaned up

Open ali-issa opened this issue 9 months ago • 7 comments

Description

This issue was filed with AI assistance. My builds were hanging indefinitely when prerender was enabled. I read the docs multiple times and reviewed related open issues (e.g. #6425), but couldn't resolve it. After ruling out misconfiguration, I spent about an hour debugging with Claude Opus and we identified the root cause below.

When using TanStack Start with prerendering enabled, the vite build process hangs indefinitely after all pages are prerendered. The process never exits, blocking CI pipelines and requiring manual termination.

Root Cause

@tanstack/router-core/dist/esm/ssr/transformStreamWithRouter.js creates 60-second setTimeout handles (lifetime timeout and serialization timeout) for each SSR-rendered page. During prerendering, these timeouts are never cleaned up because:

  1. Each call to transformStreamWithRouter() sets a lifetimeTimeoutHandle (60s) at line ~231
  2. After the app stream finishes rendering, serializationFinished is false, so a serializationTimeoutHandle (60s) is also set at line ~315
  3. The onSerializationFinished event never fires during prerendering, so tryFinish() → cleanup() is never called
  4. This leaves one timeout per prerendered page as active Node.js handles, preventing the process from exiting

With 49 prerendered pages, there are ~50 active Timeout handles keeping the event loop alive.

Reproduction

Any TanStack Start project with prerendering enabled:

// vite.config.ts
tanstackStart({
  pages: [
    { path: '/page1', prerender: { enabled: true } },
    { path: '/page2', prerender: { enabled: true } },
    // ...
  ],
})

Run vite build — the process will hang after printing "Prerendered N pages".

Environment

  • @tanstack/react-start: 1.158.3
  • @tanstack/router-core: 1.158.3
  • Vite: 7.3.1
  • Node.js: v24.7.0

Suggested Fix

Add .unref() to all setTimeout calls in transformStreamWithRouter.ts so they don't prevent the Node.js process from exiting. These are safety timeouts — they should fire if the process is still running, but shouldn't keep the process running:

// Line ~96 (early return path lifetime timeout)
  lifetimeTimeoutHandle2 = setTimeout(() => {
    // ...
  }, lifetimeMs2);
+ lifetimeTimeoutHandle2.unref();

// Line ~231 (main path lifetime timeout)
  lifetimeTimeoutHandle = setTimeout(() => {
    // ...
  }, lifetimeMs);
+ lifetimeTimeoutHandle.unref();

// Line ~315 (serialization timeout)
  serializationTimeoutHandle = setTimeout(() => {
    // ...
  }, timeoutMs);
+ serializationTimeoutHandle.unref();

Alternatively, the prerender flow should ensure onSerializationFinished fires (or cleanup() is called) after each page response is fully consumed, so the timeouts are properly cleared.

Workaround

As a temporary workaround, add process.exit(0) at the end of postServerBuild in @tanstack/start-plugin-core/dist/esm/post-server-build.js:

if (startConfig.prerender?.enabled) {
  process.exit(0);
}

ali-issa avatar Feb 06 '26 05:02 ali-issa

please provide a complete minimal reproducer project

schiller-manuel avatar Feb 15 '26 01:02 schiller-manuel

I have done a PR that should fix this #6677

mattrobrob avatar Feb 16 '26 16:02 mattrobrob

Minimal reproducer

https://github.com/alexander-zuev/tanstack-prerender-hang-repro

git clone https://github.com/alexander-zuev/tanstack-prerender-hang-repro
cd tanstack-prerender-hang-repro
pnpm install
pnpm build   # hangs after "Prerendered 2 pages"

What it does

  • 3 routes (/, /about, /terms), 2 prerendered
  • src/lib/analytics.ts creates a setInterval at module scope — simulates what PostHog, better-auth, Sentry, and similar SDKs do in production
  • After "Prerendered 2 pages" prints, the process never exits (requires Ctrl+C)

Root cause

The prerender preview server loads the full SSR bundle via dynamic import. Any module-scope persistent handle (interval, timer, WebSocket) from third-party libraries keeps the Node.js event loop alive after the preview server HTTP socket is closed.

This is compounded by the un-.unref()'d setTimeout calls in transformStreamWithRouter.ts (~lines 87, 231, 315), which add 60s timers per prerendered page that are never cleaned up.

Environment

  • @tanstack/react-start: 1.166.6
  • vite: 7.3.1
  • Node.js: v22.22.0

Image

Build is complete but the process never exits

Image

alexander-zuev avatar Mar 12 '26 10:03 alexander-zuev

Still facing the same problem, although not using Web Socket, it isn't clear what might be holding Node prerender server up.

mathewcst avatar Mar 18 '26 20:03 mathewcst

For me the build never finishes when I use createQuery in the component.

This never finishes:

function RouteComponent() {
  const test = createQuery(() => ({
    queryKey: ["posts"],
    queryFn: async (): Promise<any> => {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/posts",
      );
      return await response.json();
    },
  }));

  return <p>content</p>;
}

This does build correctly:

function RouteComponent() {
  // const test = createQuery(() => ({
  //   queryKey: ["posts"],
  //   queryFn: async (): Promise<any> => {
  //     const response = await fetch(
  //       "https://jsonplaceholder.typicode.com/posts",
  //     );
  //     return await response.json();
  //   },
  // }));

  return <p>content</p>;
}

The workaround does fix the issue in my case.

if (startConfig.prerender?.enabled) {
  process.exit(0);
}

"@tanstack/solid-query": "^5.95.0", "@tanstack/solid-router": "^1.168.2", "@tanstack/solid-start": "^1.167.3", "vite": "^8.0.1", Bun: v1.3.11

job-46 avatar Mar 23 '26 08:03 job-46

Having this issue as well. The file to patch like OP suggested is now this onenode_modules/@tanstack/start-plugin-core/dist/esm/vite/post-server-build.js. patch-package might come in handy here.

vmsp avatar Apr 21 '26 23:04 vmsp

is there any fix ?

alsherif-khalaf avatar Jul 04 '26 10:07 alsherif-khalaf