{"id":"f376460814a16fa6","repo":"brianc/node-postgres","slug":"invalid-key-value","errorCode":null,"errorMessage":"Invalid ${key}: ${value}","messagePattern":"Invalid (.+?): (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/pg-connection-string/index.js","lineNumber":198,"sourceCode":"  const poolConfig = Object.entries(config).reduce((c, [key, value]) => {\n    if (key === 'ssl') {\n      const sslConfig = value\n\n      if (typeof sslConfig === 'boolean') {\n        c[key] = sslConfig\n      }\n\n      if (typeof sslConfig === 'object') {\n        c[key] = toConnectionOptions(sslConfig)\n      }\n    } else if (value !== undefined && value !== null) {\n      if (key === 'port') {\n        // when port is not specified, it is converted into an empty string\n        // we want to avoid NaN or empty string as a values in ClientConfig\n        if (value !== '') {\n          const v = parseInt(value, 10)\n          if (isNaN(v)) {\n            throw new Error(`Invalid ${key}: ${value}`)\n          }\n\n          c[key] = v\n        }\n      } else {\n        c[key] = value\n      }\n    }\n\n    return c\n  }, Object.create(null))\n\n  return poolConfig\n}\n\n// parses a connection string into ClientConfig\nfunction parseIntoClientConfig(str) {\n  return toClientConfig(parse(str))","sourceCodeStart":180,"sourceCodeEnd":216,"githubUrl":"https://github.com/brianc/node-postgres/blob/c5e8c9a57bff6d9160ec5dbd5c4f4c1e4c460711/packages/pg-connection-string/index.js#L180-L216","documentation":"Thrown by toClientConfig() (reachable via parseIntoClientConfig or parse.toClientConfig) when the connection string's port value is non-empty but cannot be parsed into a valid integer by parseInt. The guard at index.js:196-198 attempts parseInt(value, 10), and if the result is NaN it throws 'Invalid port: <value>'. This prevents an invalid port from silently becoming NaN and causing a downstream connection failure with a confusing error.","triggerScenarios":"Calling parseIntoClientConfig('postgres://host:abc/db') or parse.toClientConfig(parse('...?port=xyz')). Any connection string where the URL port segment or the port= query parameter contains non-numeric characters. The value '' (empty string) is explicitly allowed and skipped at line 195.","commonSituations":"A port value pulled from an environment variable that is undefined and stringified to 'undefined'. A typo such as port=54_32 or a copy-paste that includes a unit suffix. A dynamically constructed connection string where the port interpolation fails.","solutions":["Correct the port value in the connection string to a plain integer (e.g., 5432).","If the port comes from an environment variable, validate it is numeric before building the connection string: Number(process.env.DB_PORT) || 5432.","Use parse() directly instead of parseIntoClientConfig if you want to handle port coercion yourself."],"exampleFix":"// before\nconst cfg = parseIntoClientConfig(`postgres://host:${process.env.DB_PORT}/db`);\n// DB_PORT was 'undefined' (string) or 'abc'\n\n// after\nconst port = Number(process.env.DB_PORT) || 5432;\nconst cfg = parseIntoClientConfig(`postgres://host:${port}/db`);","handlingStrategy":"validation","validationCode":"function validatePort(connStr) {\n  const url = new URL(connStr, 'postgres://base');\n  const port = url.port || url.searchParams.get('port');\n  if (port !== '' && port != null && isNaN(parseInt(port, 10))) {\n    throw new Error(`Port value '${port}' is not a valid integer`);\n  }\n}","typeGuard":null,"tryCatchPattern":"try {\n  const config = parseIntoClientConfig(connStr);\n} catch (err) {\n  if (/^Invalid port:/.test(err.message)) {\n    // Fix the port or use a default\n    connStr = connStr.replace(/(:)[^/]+(\\/)/, '$15432$2');\n    config = parseIntoClientConfig(connStr);\n  } else {\n    throw err;\n  }\n}","preventionTips":["Always coerce port env vars to numbers with a fallback: Number(process.env.DB_PORT) || 5432.","Validate connection strings in a config-loading layer before passing them to the driver.","Use parse() (not parseIntoClientConfig) if you want to tolerate and normalize ports yourself."],"tags":["config","connection-string","port","validation"],"analyzedSha":"c5e8c9a57bff6d9160ec5dbd5c4f4c1e4c460711","analyzedAt":"2026-08-03T18:47:28.334Z","schemaVersion":2}