Node.js "connect ECONNREFUSED 127.0.0.1" - Test Server Not Up in CI
By Kaveh Alemi·Latchkey
A test or client connected to a local port before the server was listening, so the OS refused the connection. In CI the server startup and the first request often race.
What this error means
An integration test fails with ECONNREFUSED 127.0.0.1:<port> early in the run. The server is started in the same job but is not yet accepting connections when the first request fires.
The job launches the server and immediately runs tests. On a loaded runner, startup has not finished binding the port, so the connect is refused.
The server crashed or bound a different port
If startup failed or the port came from an env var that was not set, nothing is listening where the test connects.
How to fix it
Wait for the port before testing
Use a readiness wait so tests only begin once the server accepts connections.
workflow
- run:npm start &- run:npx wait-on tcp:127.0.0.1:3000- run:npm test
Start the server inside the test setup
Boot the server in a global setup hook and await its "listening" event so there is no race.
test/setup.ts
await new Promise((resolve) =>
server.listen(3000, resolve)
);
How to prevent it
Always wait for readiness (wait-on/health check) before issuing requests.
Bind the server and await its listening event in test setup.
Surface server startup logs so a crash is distinguishable from a race.
Frequently asked questions
What causes ""connect ECONNREFUSED 127.0.0.1""?
The job launches the server and immediately runs tests. On a loaded runner, startup has not finished binding the port, so the connect is refused.
How do I fix "connect ECONNREFUSED 127.0.0.1"?
Use a readiness wait so tests only begin once the server accepts connections.
Can Latchkey fix this automatically?
Yes. Latchkey runs your GitHub Actions on managed runners that detect this failure, apply the fix, and retry the job automatically - self-healing is on by default.