Node.js "connect ECONNREFUSED 127.0.0.1" - Test Server Not Up in CI
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.
Error: connect ECONNREFUSED 127.0.0.1:3000
at TCPConnectWrap.afterConnect (node:net:1494:16)
errno: -111,
code: 'ECONNREFUSED',
address: '127.0.0.1',
port: 3000Common causes
Tests start before the server listens
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.
- run: npm start &
- run: npx wait-on tcp:127.0.0.1:3000
- run: npm testStart the server inside the test setup
Boot the server in a global setup hook and await its "listening" event so there is no race.
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.