Socket port is outside the valid range 0-65535
Production Risk
Server fails to start if port is invalid; validate at startup.
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.
- 1Port number computed from user input overflows or is negative
- 2Typo resulting in a port > 65535
- 3Port from config is a string that does not parse to a valid number
Triggered when a networking API validates a port number and finds it out of range.
const net = require('net');
const server = net.createServer();
server.listen(99999); // invalid port — throws ERR_SOCKET_BAD_PORTexpected 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
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.
const net = require('net');
const server = net.createServer();
server.listen(99999); // invalid port — throws ERR_SOCKET_BAD_PORT // this triggers ERR_SOCKET_BAD_PORTtry {
// 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
}
}// Validate inputs before calling the operation
function safe_err_socket_bad_port(...args) {
// validate args here
return performOperation(...args)
}✕ Use unvalidated port numbers from environment variables or user input
Out-of-range ports cause immediate errors and may indicate misconfiguration.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev