Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Re-use randomly selected dev server port for automatic restarts #72771

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions packages/next/src/cli/next-dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ const nextDev = async (
}
}

const port = options.port
let port = options.port

if (isPortIsReserved(port)) {
printAndExit(getReservedPortExplanation(port), 1)
Expand Down Expand Up @@ -299,6 +299,12 @@ const nextDev = async (
if (msg.nextWorkerReady) {
child?.send({ nextWorkerOptions: startServerOptions })
} else if (msg.nextServerReady && !resolved) {
if (msg.port) {
// Store the used port in case a random one was selected, so that
// it can be re-used on automatic dev server restarts.
port = parseInt(msg.port, 10)
}

resolved = true
resolve()
}
Expand All @@ -323,7 +329,8 @@ const nextDev = async (
sync: true,
})
}
return startServer(startServerOptions)

return startServer({ ...startServerOptions, port })
}
// Call handler (e.g. upload telemetry). Don't try to send a signal to
// the child, as it has already exited.
Expand Down
7 changes: 5 additions & 2 deletions packages/next/src/server/lib/start-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,11 @@ export async function startServer(
)
}

// expose the main port to render workers
// Store the selected port to:
// - expose it to render workers
// - re-use it for automatic dev server restarts with a randomly selected port
process.env.PORT = port + ''

process.env.__NEXT_PRIVATE_ORIGIN = appUrl

// Only load env and config in dev to for logging purposes
Expand Down Expand Up @@ -420,7 +423,7 @@ if (process.env.NEXT_PRIVATE_WORKER && process.send) {
'memory.heapUsed',
String(memoryUsage.heapUsed)
)
process.send({ nextServerReady: true })
process.send({ nextServerReady: true, port: process.env.PORT })
}
})
process.send({ nextWorkerReady: true })
Expand Down
Loading