Skip to content

Conversation

c0va23
Copy link

@c0va23 c0va23 commented Sep 5, 2025

Hi!

Issue

As my react-router-based (latest release version) project grew, I encountered the following error when running react-router (as an Express.js app) in development mode:

Output of `npm run dev`
(ins)❯ npm run dev

> dev
> NODE_ENV=development node --watch --watch-path server.js server.js

Starting development server
9:17:48 AM [vite] (client) Re-optimizing dependencies because lockfile has changed
Server is running on http://localhost:3030
Received exit, shutting down gracefully...
node:internal/fs/watchers:254
    const error = new UVException({
                  ^

Error: ENOSPC: System limit for number of file watchers reached, watch 'PROJECT_DIR/.devenv/profile/lib/bitcode/postgres/utils/cache/attoptcache.bc'
    at FSWatcher.<computed> (node:internal/fs/watchers:254:19)
    at Object.watch (node:fs:2534:36)
    at createFsWatchInstance (file://PROJECT_DIR/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:16662:16)
    at setFsWatchListener (file://PROJECT_DIR/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:16704:14)
    at NodeFsHandler$1._watchWithNodeFs (file://PROJECT_DIR/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:16824:20)
    at NodeFsHandler$1._handleFile (file://PROJECT_DIR/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:16868:24)
    at NodeFsHandler$1._addToNodeFs (file://PROJECT_DIR/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:17042:26)
Emitted 'error' event on FSWatcher instance at:
    at FSWatcher._handleError (file://PROJECT_DIR/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:17850:148)
    at NodeFsHandler$1._addToNodeFs (file://PROJECT_DIR/node_modules/vite/dist/node/chunks/dep-C6pp_iVS.js:17047:18) {
  errno: -28,
  syscall: 'watch',
  code: 'ENOSPC',
  path: 'PROJECT_DIR/.devenv/profile/lib/bitcode/postgres/utils/cache/attoptcache.bc',
  filename: 'PROJECT_DIR/.devenv/profile/lib/bitcode/postgres/utils/cache/attoptcache.bc'
}

Invistigation

  1. The code before my changes passed the undefined value to the watch option of the Vite server, which enabled the watch mode: https://github.com/vitejs/vite/blob/bcc31449c0c4f852ccb1eedda1842bc7ded23d01/packages/vite/src/node/server/index.ts#L493
  2. And the undefeined watch option falls back to an empty watch option, which causes starting the Vite server with default config: https://github.com/vitejs/vite/blob/main/packages/vite/src/node/watch.ts#L57
  3. Because the Vite with the reactRouter() plugin is trying to subscribe to all files in the project dir with some hard-coded exceptions: https://github.com/vitejs/vite/blob/bcc31449c0c4f852ccb1eedda1842bc7ded23d01/packages/vite/src/node/watch.ts#L58

Solution

In my simple solution, I just copied the server.watch option from the vite.config.(ts|js) config to the Vite server inside the reactRouter() plugin to respect the project config within.

My small fix solves this problem. Also, my fix sped up the development server startup time several times (from ~1 minute to ~10 seconds).

A project context

For the context, some files from my project can be relevant to the issue:

Content of `server.js`
// eslint-disable-next-line import/no-unassigned-import, import/extensions
import './server/instrumentation.js'

import compression from 'compression'
import express, { static as expressStatic } from 'express'
import { StatusCodes } from 'http-status-codes'
import morgan from 'morgan'
import process from 'node:process'
// eslint-disable-next-line import/extensions
import { tracingMiddleware } from './server/middlewares/otel.js'
import { createWriteStream } from 'node:fs'

// Short-circuit the type-checking of the built output.
const buildDirectory = `build/${process.env.NODE_ENV}`
const BUILD_PATH = `./${buildDirectory}/server/index.js`

const DEVELOPMENT = process.env.NODE_ENV === 'development'

const SERVER_PORT = Number.parseInt(process.env.SERVER_PORT ?? '3030')
const SERVER_HOST = process.env.SERVER_HOST ?? 'localhost'

const app = express()

const { SERVER_LOG_FILE } = process.env

const serverLogStream = SERVER_LOG_FILE
	? createWriteStream(SERVER_LOG_FILE, {
		flags: 'a',
	})
	: process.stdout

app.use(morgan(
	'tiny',
	{
		stream: serverLogStream,
	}
))
app.use(compression())
app.disable('x-powered-by')

app.use(tracingMiddleware)

if (DEVELOPMENT) {
	console.log('Starting development server')
	// eslint-disable-next-line import/no-extraneous-dependencies
	const vite = await import('vite')
	const viteDevelopmentServer = await vite.createServer({
		server: {
			middlewareMode: true,
		},
	})

	// Workaround form React Developer Tools browser extension
	app.get(/\/installHook.js.map$/, (_, response) => {
		response.status(StatusCodes.NOT_FOUND).send('Not found')
	})

	app.use(viteDevelopmentServer.middlewares)
	app.use(async (
		request,
		response,
		next,
	) => {
		try {
			const source = await viteDevelopmentServer.ssrLoadModule('./server/app.ts')
			await source.app(
				request,
				response,
				next,
			)
		} catch (error) {
			if (typeof error === 'object' && error instanceof Error) {
				viteDevelopmentServer.ssrFixStacktrace(error)
			}
			next(error)
		}
	})
} else {
	console.log(`Starting server from ${buildDirectory}`)

	app.use(
		'/assets',
		expressStatic(
			`${buildDirectory}/client/assets`,
			{
				immutable: true,
				maxAge: '1y',
			},
		),
	)
	app.use(expressStatic(
		`${buildDirectory}/client`,
		{ maxAge: '1h' },
	))
	app.use(await import(BUILD_PATH).then((module_) => module_.app))
}


const server = app.listen(
	SERVER_PORT,
	SERVER_HOST,
	() => {
		console.log(`Server is running on http://${SERVER_HOST}:${SERVER_PORT}`)
	},
)

const exitSignals = [
	'SIGTERM',
	'SIGINT',
	'exit',
]

for (const signal of exitSignals) {
	process.once(signal, () => {
		console.log(`Received ${signal}, shutting down gracefully...`)

		server.close((error) => {
			if (error) {
				console.error('Error shutting down server:', error)
			} else {
				console.log('Server shut down successfully.')
			}

			const successExitCode = 0

			process.exit(successExitCode)
		})
	})
}
Content of `vite.config.ts`
import { reactRouter } from '@react-router/dev/vite'
import tailwindcss from '@tailwindcss/vite'
import { safeRoutes } from 'safe-routes/vite'
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
import { visualizer } from 'rollup-plugin-visualizer'
import {
	readIgnoreFileGlobs, viteWatchIgnoreMatcher,
} from './scripts/utilities/ignore-file.mjs'

const vscIgnoreGlobs = await readIgnoreFileGlobs('.gitignore')
const watchIgnoredMatcher = viteWatchIgnoreMatcher(
	process.cwd(),
	vscIgnoreGlobs,
	['.react-router/**'],
)


export default defineConfig(({ isSsrBuild }) => ({
	build: {
		target: isSsrBuild ? 'node22' : undefined,
		rollupOptions: isSsrBuild
			? {
				input: './server/app.ts',
				external: ['@prisma/client'],
			}
			: undefined,
	},
	server: {
		watch: {
			awaitWriteFinish: {
				stabilityThreshold: 100, // ms, debounce for file auto-formatting
			},
			ignored: [
				'**/e2e/**',
				'**/docs/**',
				'**/*.test.*',
				'**/*.spec.*',
				watchIgnoredMatcher,
			],
		},
	},
	plugins: [
		...process.env.ROLLUP_VISUALIZER === 'enabled'
			? [
				visualizer({
					gzipSize: true,
					brotliSize: true,
					emitFile: true,
					filename: 'bundle-stats.html',
				}),
			]
			: [],
		tailwindcss(),
		reactRouter(),
		tsconfigPaths(),
		safeRoutes(),
	],
}))
Content of `scripts/utilities/ignore-file.mjs`
import ignore from 'ignore'
import fsPromises from 'node:fs/promises'
/**
 * Parse ignore file and return globs.
 *
 * @param {string} filePath to ignore.
 * @returns {Promise<string[]>} return ignore globs.
 */
export async function readIgnoreFileGlobs(filePath) {
	const fileContentBytes = await fsPromises.readFile(filePath)
	const fileContent = fileContentBytes.toString()

	return fileContent.split('\n').filter((line) => {
		const trimmedLine = line.trim()
		return trimmedLine.length > 0
			&& !trimmedLine.startsWith('#')
			&& !trimmedLine.startsWith('!')
	})
}

/**
 * @param {string} pathPrefix
 * @param {string[]} ignoreGlobs
 * @param {string[]} whitelistGlobs
 * @returns
 */
export function viteWatchIgnoreMatcher(
	pathPrefix,
	ignoreGlobs,
	whitelistGlobs,
) {
	const ignoreMatcher = ignore().add(ignoreGlobs)
	const notIgnoreMatcher = ignore().add(whitelistGlobs)
	const pathSeparatorLength = 1

	/**
	 * @param {string} path
	 */
	return (path) => {
		if (!path.startsWith(pathPrefix)) {
			return true
		}

		const relativePath = path.slice(pathPrefix.length + pathSeparatorLength)

		if (relativePath.length === 0) {
			return false
		}

		const whiteListed = notIgnoreMatcher.test(relativePath)
		if (whiteListed.ignored) {
			return false
		}

		const ignored = ignoreMatcher.test(relativePath)
		if (ignored.ignored) {
			return true
		}

		return false
	}
}

Copy link

changeset-bot bot commented Sep 5, 2025

🦋 Changeset detected

Latest commit: b9e3f7f

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
@react-router/dev Patch
@react-router/fs-routes Patch
@react-router/remix-routes-option-adapter Patch
create-react-router Patch
react-router Patch
react-router-dom Patch
@react-router/architect Patch
@react-router/cloudflare Patch
@react-router/express Patch
@react-router/node Patch
@react-router/serve Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@remix-cla-bot
Copy link
Contributor

remix-cla-bot bot commented Sep 5, 2025

Hi @c0va23,

Welcome, and thank you for contributing to React Router!

Before we consider your pull request, we ask that you sign our Contributor License Agreement (CLA). We require this only once.

You may review the CLA and sign it by adding your name to contributors.yml.

Once the CLA is signed, the CLA Signed label will be added to the pull request.

If you have already signed the CLA and received this response in error, or if you have any questions, please contact us at [email protected].

Thanks!

- The Remix team

@remix-cla-bot
Copy link
Contributor

remix-cla-bot bot commented Sep 5, 2025

Thank you for signing the Contributor License Agreement. Let's get this merged! 🥳

@c0va23 c0va23 changed the title Copy 'server.watch config option from vite.config.(ts|js)` to child vite server in development mode Copy server.watch config option from vite.config.(ts|js) to child vite server in development mode Sep 5, 2025
@c0va23 c0va23 force-pushed the feature/bypass-server-watch-config branch from 3c6eef8 to b9e3f7f Compare September 5, 2025 14:25
@c0va23 c0va23 requested a review from timdorr September 6, 2025 04:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants