#4661·nitro

vite dev: scan-dir and rootDir watchers are never closed when the vite server closes or restarts

Author: light-merlin-darkCreated Sep 24, 2026Updated Sep 28, 2026

Environment

  • nitro 3.0.260903-beta (also 3.0.1-alpha.2), vite 8.3.0
  • Node v22.22.3 and v24.21.0, macOS 26.6.2 (arm64)

Reproduction

https://gist.github.com/light-merlin-dark/4bf3cef36788493c770dc05520733469

bash
npm install
npm run repro   # node repro.mjs 3

Describe the bug

configureViteDevServer opens a chokidar watcher on the scan dirs and an fs.watch on rootDir. It closes both only in nitro.hooks.hook("close"). In vite dev, nitro.close() is never called when the vite server closes or restarts in process (a config or .env change calls server.restart()). Each restart therefore leaves both watchers open. Their change closures capture nitroEnv, which keeps the previous environment and its module graph reachable.

The repro counts fs.watch watchers opened from nitro that are not yet closed:

{"restarts":3,"nitroFsWatchersAfterStart":1,"nitroFsWatchersAfterRestarts":4, ...}
{"nitroFsWatchersAfterClose":4}

Even after server.close(), all 4 stay open.

A heap snapshot of a real app shows the path FSEventWrap → FSWatcher → _events.change → closure → nitroEnv → FetchableDevEnvironment → EnvironmentModuleGraph for each previous server.

Closing the watchers together with the nitro dev environment fixes it in the repro. After 3 restarts 1 watcher is open, and after close 0:

javascript
const closeWatchers = () => {
  scanDirsWatcher.close();
  rootDirWatcher.close();
};
nitro.hooks.hook("close", closeWatchers);
const closeNitroEnv = nitroEnv.close.bind(nitroEnv);
nitroEnv.close = async () => {
  closeWatchers();
  await closeNitroEnv();
};

Overriding close on the instance is only the smallest change that proves it. A close() on the environment class, next to the existing devServer.close(), may be the cleaner place.

Additional context

The env-runner worker leak had the same shape: one ~150 MB worker per restart. It is already fixed in the beta by FetchableDevEnvironment.close() calling this.devServer.close(). The watchers are what remains.

Logs

N/A

By Merlin (rbeckner.com) and his AI agent (Claude Code, Claude Opus 5.5, thinking on: low).