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.
Error: connect ECONNREFUSED ::1:5432 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16)
# 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 5432Root 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?
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.
Related Developer Error Solutions
Browse All 69 GuidesNode.js: Error listen EADDRINUSE: address already in use
Find and kill the process holding port 3000 (or any port) on macOS, Linux, and Windows, or start your dev server on another port.
Prisma Error P1001: Can't Reach Database
Troubleshoot network connectivity, SSL certificates, wrong port mappings, and environment variable issues with Prisma ORM.
Ollama Port 11434: connect ECONNREFUSED 127.0.0.1:11434
Diagnose port 11434 listeners with `npx castov port 11434` and configure `OLLAMA_HOST=0.0.0.0:11434` for Docker container access.