Skip to content
Latchkey

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

  1. Convert the env value to a number with a sensible default.
  2. Pass the integer to the network call.
JavaScript
const port = Number(process.env.PORT) || 3000;
server.listen(port);

Set the PORT variable in CI

  1. Provide PORT in the workflow env for the step that listens or connects.
  2. 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.

Frequently asked questions

What causes ""RangeError [ERR_SOCKET_BAD_PORT]""?
process.env.PORT is undefined in CI, and Number(undefined) is NaN, which fails port validation.
How do I fix "RangeError [ERR_SOCKET_BAD_PORT]"?
Coerce and default the port

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card