Skip to main content
Network & HTTP · Developer Error Resolution Lab

Fix 'connect ECONNREFUSED ::1' in Node.js 18+ When localhost Resolves to IPv6

Node.js 17+ no longer reorders DNS results to IPv4 first, so 'localhost' hits ::1 while your database only listens on 127.0.0.1.

Triggered Error Message:

Error: connect ECONNREFUSED ::1:5432 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16)

Customize Solution for Your Environment
# Option 1: replace localhost with 127.0.0.1 in your connection string
HOST=127.0.0.1 PORT=5432

# Option 2: prefer IPv4 for the whole Node process
NODE_OPTIONS="--dns-result-order=ipv4first" npm run dev

# Option 3: in code (Node 18+)
import dns from "node:dns";
dns.setDefaultResultOrder("ipv4first");

# Confirm what is actually listening on 5432
npx castov port 5432

Root Cause & Mechanism Analysis

Why does this error occur?

Since Node.js 17, `dns.lookup` returns addresses in the order the OS provides (`verbatim`). On many systems `localhost` resolves to the IPv6 address `::1` first, but services like PostgreSQL, Redis, or a Docker-published port often listen only on IPv4 `127.0.0.1`.

Frequently Asked Questions

Why did this start after upgrading Node?
Node 17 changed the default DNS result order from ipv4first to verbatim. Code that relied on localhost meaning 127.0.0.1 broke on IPv6-first systems.
DEVSECOPS & CI/CD PARTNER2 Slots Open

Need Zero-Knowledge .env Secret Sync Across Your Engineering Team?

Explore Castov Env Vault for client-side AES-256-GCM encrypted environment sharing, or sponsor this engineering hub.

Browse All 69 Guides