Skip to content

Commit c047d75

Browse files
authored
Port unavailable handling (#673)
1 parent bd6a00a commit c047d75

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

server/index.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ installGlobals()
1616

1717
const MODE = process.env.NODE_ENV ?? 'development'
1818
const IS_PROD = MODE === 'production'
19+
const IS_DEV = MODE === "development"
1920

2021
const createRequestHandler = IS_PROD
2122
? Sentry.wrapExpressCreateRequestHandler(_createRequestHandler)
@@ -220,28 +221,29 @@ const desiredPort = Number(process.env.PORT || 3000)
220221
const portToUse = await getPort({
221222
port: portNumbers(desiredPort, desiredPort + 100),
222223
})
224+
const portAvailable = desiredPort === portToUse
225+
if (!portAvailable && !IS_DEV) {
226+
console.log(`⚠️ Port ${desiredPort} is not available.`)
227+
process.exit(1)
228+
}
223229

224230
const server = app.listen(portToUse, () => {
225-
const addy = server.address()
226-
const portActuallyUsed =
227-
addy === null || typeof addy === 'string' ? 0 : addy.port
228-
229-
if (portActuallyUsed !== desiredPort) {
231+
if (!portAvailable) {
230232
console.warn(
231233
chalk.yellow(
232-
`⚠️ Port ${desiredPort} is not available, using ${portActuallyUsed} instead.`,
234+
`⚠️ Port ${desiredPort} is not available, using ${portToUse} instead.`,
233235
),
234236
)
235237
}
236238
console.log(`🚀 We have liftoff!`)
237-
const localUrl = `http://localhost:${portActuallyUsed}`
239+
const localUrl = `http://localhost:${portToUse}`
238240
let lanUrl: string | null = null
239241
const localIp = ipAddress() ?? 'Unknown'
240242
// Check if the address is a private ip
241243
// https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
242244
// https://github.com/facebook/create-react-app/blob/d960b9e38c062584ff6cfb1a70e1512509a966e7/packages/react-dev-utils/WebpackDevServerUtils.js#LL48C9-L54C10
243245
if (/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(localIp)) {
244-
lanUrl = `http://${localIp}:${portActuallyUsed}`
246+
lanUrl = `http://${localIp}:${portToUse}`
245247
}
246248

247249
console.log(

0 commit comments

Comments
 (0)