Skip to content
Source
Sign inSign up
TanStack/router

fix(start): force close preview server connections after prerendering #6677

Closedmattrobrob(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/6677/headopened

Summary

The prerender step hangs indefinitely after successfully completing when the application imports modules that create persistent handles (websocket connections, flush intervals, timers, etc.).

During prerendering, startPreviewServer loads the full server bundle via Nitro's preview plugin. If the application uses libraries that create persistent connections at module scope (e.g. PostHog analytics, Zero sync engine, OpenAuth client), those handles keep the Node.js event loop alive. Calling previewServer.close() only shuts down the HTTP server — it does not clean up resources from dynamically imported application modules.

This causes the build process to hang after printing "Prerendered N pages", requiring a manual ^C to terminate.

Fix

Force-close all active connections before closing the preview server, since it is an ephemeral server used only for prerendering during the build step. Graceful shutdown of application-level resources is not necessary here.

Test plan

  • Build a TanStack Start app with spa: { enabled: true } that imports a library creating persistent handles (e.g. a websocket client)
  • Run vite build
  • Verify the build completes and exits cleanly after prerendering
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-plugin-core

    2. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      📝 Walkthrough

      Walkthrough

      Adds explicit process exit (process.exit(0)) after closing the Vite preview server in the prerender flow. This ensures the Node.js process terminates cleanly after completing prerender operations and cleanup procedures.

      Changes

      Cohort / File(s)Summary
      Process Termination
      packages/start-plugin-core/src/prerender.ts
      Added explicit process exit after Vite preview server closure to ensure proper process termination post-cleanup.

      Estimated code review effort

      🎯 1 (Trivial) | ⏱️ ~3 minutes

      • TanStack/router#6619: Also addresses prerender control flow to prevent process hanging, implementing an early return when no tasks are present.

      Poem

      🐰 A hop, a skip, a cleanup done, The preview server's race is run. With exit called, the process flies, No hanging threads beneath the skies! ✨

      🚥 Pre-merge checks | ✅ 3 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (3 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and specifically describes the main change: forcing preview server connections to close after prerendering, which directly addresses the hanging issue in the prerender flow.
      Merge Conflict Detection✅ Passed✅ No merge conflicts detected when merging into main
      Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing touches
      • 📝 Generate docstrings
        🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    3. Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (1)
      packages/start-plugin-core/src/prerender.ts (1)

      108-112: ⚠️ Potential issue | 🟠 Major

      process.exit(0) after a caught error masks prerender failures.

      When prerenderPages throws, the catch block logs the error but doesn't re-throw. Then finally runs process.exit(0), so the process exits with a success code despite the failure. This will silently pass in CI/CD pipelines.

      Consider exiting with a non-zero code when an error was caught:

      Proposed fix
      +  let exitCode = 0
         try {
           // Crawl all pages
           const pages = await prerenderPages({ outputDir })
       
           logger.info(`Prerendered ${pages.length} pages:`)
           pages.forEach((page) => {
             logger.info(`- ${page}`)
           })
         } catch (error) {
           logger.error(error)
      +    exitCode = 1
         } finally {
           await previewServer.close()
      -    process.exit(0)
      +    process.exit(exitCode)
         }
      🧹 Nitpick comments (1)
      packages/start-plugin-core/src/prerender.ts (1)

      110-113: process.exit() prevents callers from performing post-prerender cleanup.

      Since prerender is an exported async function, callers awaiting it will never receive a resolved/rejected promise — the process just terminates. If this is acceptable for the current usage (build-time only, last step), it's fine, but it's worth documenting with a comment so future maintainers understand the intentional early termination.

      Also, if previewServer.close() itself throws, process.exit(0) won't execute and the original hanging problem could still occur. Consider wrapping close() in a try/catch within the finally block if robustness matters here.

      Suggested hardening
         } finally {
      -    await previewServer.close()
      -    process.exit(0)
      +    try {
      +      await previewServer.close()
      +    } catch (e) {
      +      // Ignore close errors; we're exiting anyway
      +    }
      +    // Force exit to avoid hanging on persistent handles (e.g. websockets, timers)
      +    process.exit(exitCode)
         }
    4. not a fan of this approach. there might be other things running after prerendering. users should not create those persistent connections during prerendering

    5. mattrobrob(GitHub profile, opens in a new tab)commented

      not a fan of this approach. there might be other things running after prerendering. users should not create those persistent connections during prerendering

      @schiller-manuel how would someone do that if their application is built around a websocket connection? Is there a flag to say when an app is prerendering?

      This wasn't an issue before either so something must have changed recently

Sign in to join this conversation.