Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readNode

Fix ECONNREFUSED ::1 on localhost in Node

Diagnose an IPv6 loopback connection failure and point the client at the address your Node server listens on.

Your server is up, curl http://localhost:4100 answers, and the same URL from fetch in a Node script dies with TypeError: fetch failed. Scroll past the stack and the cause is one line.

TypeError: fetch failed
  [cause]: Error: connect ECONNREFUSED ::1:4100
    code: 'ECONNREFUSED',
    address: '::1',
    port: 4100

The ::1 is the tell. Node resolved localhost to the IPv6 loopback address and connected there, while your server is listening on 127.0.0.1, the IPv4 one. No process is on the IPv6 side, so the kernel refuses.

diagram

Where fetch connects, and where the server listens

fetch resolves localhost to ::1 first and connects there, while the server only listens on 127.0.0.1.

Why Node picks ::1

Two things line up. Since Node 17, dns.lookup returns addresses in the order the operating system gives them; older versions sorted IPv4 first. A hosts file maps localhost to both 127.0.0.1 and ::1, and on many machines ::1 comes back first.

The other half is the server. Somewhere it says server.listen(4100, '127.0.0.1'), or the dev tool you started defaults to that host.

Node 18.0–18.17 defaults to trying a single address. Node 18.18 and 20.0 enabled autoSelectFamily by default, so the client can try IPv4 if the lookup returns both families and IPv6 fails.

Fix it on the server

For a local-only service that listens on IPv4, use http://127.0.0.1:4100/ in the client. If the service should accept connections from other devices too, you can omit the host.

server.listen(4100, () => {
  console.log(server.address())
})

With IPv6 available, Node listens on the unspecified address ::. Many systems accept IPv4 on that socket too. With no IPv6 support, Node listens on 0.0.0.0. Both are wildcard addresses and can expose the service beyond loopback.

Fix it on the client

If the client must keep using localhost, set the DNS result order before it makes the request. This changes the order for other lookups on the same thread too.

import dns from 'node:dns'
dns.setDefaultResultOrder('ipv4first')

const res = await fetch('http://localhost:4100/')
console.log(res.status, await res.text()) // 200 hello

The same switch exists as a flag, node --dns-result-order=ipv4first script.mjs, for code you cannot edit. Both have been in Node since 16.4, and let you keep the existing URL. A worker thread needs its own call if you use the function.