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.
node
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.
JavaScript
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.
GitHub Actions
- 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.
Related guides
Node "listen EACCES permission denied" on a Privileged Port in CI - Fix ItFix the Node.js "listen EACCES: permission denied" error in CI by binding to an unprivileged port above 1024…
Node EADDRINUSE "address already in use" for a Test Server in CI - Fix Port ConflictsFix the Node.js EADDRINUSE "address already in use" error for a test server in CI by closing the previous lis…
Node ERR_INVALID_ARG_TYPE in CI - Pass the Right Argument TypeFix the Node.js ERR_INVALID_ARG_TYPE error in CI by passing the argument type a core API expects instead of u…