ERR_SOCKET_BAD_PORT
Node.jsERRORNotableDNSHIGH confidence

Socket port is outside the valid range 0-65535

Production Risk

Server fails to start if port is invalid; validate at startup.

What this means

Thrown when a port number passed to a socket, server, or DNS API is not in the valid range of 0 to 65535. TCP and UDP port numbers are 16-bit unsigned integers; values outside this range are invalid.

Why it happens
  1. 1Port number computed from user input overflows or is negative
  2. 2Typo resulting in a port > 65535
  3. 3Port from config is a string that does not parse to a valid number
How to reproduce

Triggered when a networking API validates a port number and finds it out of range.

trigger — this will error
trigger — this will error
const net = require('net');
const server = net.createServer();
server.listen(99999); // invalid port — throws ERR_SOCKET_BAD_PORT

expected output

RangeError [ERR_SOCKET_BAD_PORT]: Port should be >= 0 and < 65536. Received 99999

Fix

Validate port numbers before use

WHEN When port comes from configuration or user input

Validate port numbers before use
const port = parseInt(process.env.PORT, 10);
if (!Number.isInteger(port) || port < 0 || port > 65535) {
  throw new Error(`Invalid port: ${port}`);
}
server.listen(port);

Why this works

Explicit range validation ensures only valid port numbers are passed to networking APIs.

Code examples
Triggerjs
const net = require('net');
const server = net.createServer();
server.listen(99999); // invalid port — throws ERR_SOCKET_BAD_PORT  // this triggers ERR_SOCKET_BAD_PORT
Handle in try/catchjs
try {
  // operation that may throw ERR_SOCKET_BAD_PORT
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_SOCKET_BAD_PORT') {
    console.error('ERR_SOCKET_BAD_PORT:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_socket_bad_port(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Use unvalidated port numbers from environment variables or user input

Out-of-range ports cause immediate errors and may indicate misconfiguration.

Sources
Official documentation ↗

Node.js Error Codes Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors