Node ERR_SOCKET_BAD_PORT in CI - Pass a Valid Port Number
ERR_SOCKET_BAD_PORT means a network API received a port that is not a valid integer between 0 and 65535, commonly because an env var was undefined or a string.
What this error means
A listen or connect call throws RangeError [ERR_SOCKET_BAD_PORT]: options.port should be >= 0 and < 65536. Received NaN (or a string), because the port value was bad.
RangeError [ERR_SOCKET_BAD_PORT]: options.port should be >= 0 and < 65536.
Received NaN.
at validatePort (node:internal/validators:217:11)
at Server.listen (node:net:1726:5) { code: 'ERR_SOCKET_BAD_PORT' }Common causes
An unset PORT env var resolved to undefined
process.env.PORT is undefined in CI, and Number(undefined) is NaN, which fails port validation.
A string port not coerced to a number
An env var is a string and some APIs require an integer, so an out-of-range or non-numeric value is rejected.
How to fix it
Coerce and default the port
- Convert the env value to a number with a sensible default.
- Pass the integer to the network call.
const port = Number(process.env.PORT) || 3000;
server.listen(port);Set the PORT variable in CI
- Provide PORT in the workflow env for the step that listens or connects.
- Re-run so the port is a valid integer.
- run: node server.js
env:
PORT: '3000'How to prevent it
- Always coerce env-derived ports to numbers with a default, validate the range at startup, and provide PORT explicitly in CI rather than relying on an ambient value.