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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →