New apps created with `remix new` report HMR port conflicts without starting the app server, avoiding a secondary `EPIPE` error from the child process. Existing apps can apply the same startup and shutdown changes in `hmr.ts`: ```diff --- a/hmr.ts +++ b/hmr.ts @@ -1 +1,2 @@ +import { once } from 'node:events' import * as http from 'node:http' @@ -12,35 +13,47 @@ -const hmrRunner = run('server.ts', { - env: { - ...process.env, - PORT: String(appPort), - HMR_PROXY_PORT: String(hmrProxyPort), - }, - nodeArgs: ['--import', 'remix/node-tsx', '--import', 'remix/component-hmr/node'], - browserHmrChannel: { port: hmrEventPort }, -}) - -const server = http.createServer( - createRequestListener( - createHmrReadyFetch( - hmrRunner, - createFetchProxy(`http://127.0.0.1:${appPort}`, { - xForwardedHeaders: true, - }), - ), - ), -) - -server.listen(hmrProxyPort, '127.0.0.1') +const server = http.createServer() let shuttingDown = false +let hmrRunner: ReturnType | undefined -function shutdown() { +process.on('SIGINT', () => shutdown()) +process.on('SIGTERM', () => shutdown()) + +try { + server.listen(hmrProxyPort, '127.0.0.1') + await once(server, 'listening') + + if (!shuttingDown) { + hmrRunner = run('server.ts', { + env: { + ...process.env, + PORT: String(appPort), + HMR_PROXY_PORT: String(hmrProxyPort), + }, + nodeArgs: ['--import', 'remix/node-tsx', '--import', 'remix/component-hmr/node'], + browserHmrChannel: { port: hmrEventPort }, + }) + + server.on( + 'request', + createRequestListener( + createHmrReadyFetch( + hmrRunner, + createFetchProxy(`http://127.0.0.1:${appPort}`, { + xForwardedHeaders: true, + }), + ), + ), + ) + } +} catch (error) { + console.error(`Failed to start HMR on http://127.0.0.1:${hmrProxyPort}:`, error) + shutdown(1) +} + +function shutdown(exitCode = 0) { if (shuttingDown) return shuttingDown = true - server.close(() => hmrRunner.close().finally(() => process.exit(0))) + server.close(() => Promise.resolve(hmrRunner?.close()).finally(() => process.exit(exitCode))) server.closeAllConnections() } - -process.on('SIGINT', shutdown) -process.on('SIGTERM', shutdown) ```