Fix Error: connect ECONNREFUSED 127.0.0.1:5000 in Express
This error occurs when http-proxy-middleware or a similar proxy tries to forward a request to an upstream server that is not running or is unreachable. The TCP connection is refused because nothing is listening on the target port. Fix it by verifying the upstream service is running, adding health checks, and handling proxy errors gracefully.
Reading the Stack Trace
Here's what each line means:
- at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1595:16): The TCP connection attempt to 127.0.0.1:5000 was refused because no process is listening on that port.
- at ClientRequest.<anonymous> (/app/node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js:172:24): The http-proxy library attempted to forward the incoming request to the target server and received the connection refusal.
- at Socket.socketErrorListener (node:_http_client:500:9): Node's HTTP client detected the socket error and is propagating it up through the proxy middleware.
Common Causes
1. Upstream service not running
The target backend service has not been started, crashed, or is still booting when the proxy tries to forward requests.
const { createProxyMiddleware } = require('http-proxy-middleware');
app.use('/api', createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true
}));
// Backend on port 5000 is not running
2. Wrong target URL or port
The proxy target URL is misconfigured, pointing to the wrong host or port where no service is listening.
app.use('/api', createProxyMiddleware({
target: 'http://localhost:5000', // Should be port 5001
changeOrigin: true
}));
3. No error handler on proxy
The proxy middleware lacks an onError handler, so ECONNREFUSED crashes the Express process instead of returning a 502.
app.use('/api', createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true
// No onError handler
}));
The Fix
Add an onError handler to the proxy middleware that catches ECONNREFUSED and other connection errors, returning a 502 Bad Gateway response instead of crashing. Use an environment variable for the target URL to avoid hardcoding.
const { createProxyMiddleware } = require('http-proxy-middleware');
app.use('/api', createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true
}));
const { createProxyMiddleware } = require('http-proxy-middleware');
app.use('/api', createProxyMiddleware({
target: process.env.API_TARGET || 'http://localhost:5000',
changeOrigin: true,
on: {
error: (err, req, res) => {
console.error('Proxy error:', err.code, err.message);
if (!res.headersSent) {
res.status(502).json({
error: 'Bad Gateway',
message: 'The upstream service is unavailable. Please try again later.'
});
}
}
}
}));
Testing the Fix
const request = require('supertest');
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const http = require('http');
function createApp(target) {
const app = express();
app.use('/api', createProxyMiddleware({
target,
changeOrigin: true,
on: {
error: (err, req, res) => {
if (!res.headersSent) {
res.status(502).json({ error: 'Bad Gateway' });
}
}
}
}));
return app;
}
describe('Proxy middleware', () => {
it('returns 502 when upstream is unreachable', async () => {
const res = await request(createApp('http://localhost:59999'))
.get('/api/data');
expect(res.status).toBe(502);
expect(res.body.error).toBe('Bad Gateway');
});
it('proxies successfully when upstream is available', async () => {
const upstream = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ proxied: true }));
});
await new Promise(resolve => upstream.listen(0, resolve));
const port = upstream.address().port;
const res = await request(createApp(`http://localhost:${port}`))
.get('/api/data');
expect(res.status).toBe(200);
expect(res.body.proxied).toBe(true);
upstream.close();
});
});
Run your tests:
npx jest --testPathPattern=proxy
Pushing Through CI/CD
git checkout -b fix/express-proxy-error,git add src/middleware/proxy.js src/__tests__/proxy.test.js,git commit -m "fix: add error handler for proxy ECONNREFUSED",git push origin fix/express-proxy-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npx jest --coverage
- run: npm run lint
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
const { initBugStack } = require('bugstack-sdk')
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm proxy errors return 502 instead of crashing.
- Open a pull request with the proxy error handling changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the proxy works in staging before promoting to production.
Frequently Asked Questions
BugStack tests the proxy with both reachable and unreachable upstream targets, verifies correct 502 responses on failure, and confirms successful proxying on success before marking it safe.
Every fix is delivered as a pull request with full CI validation. Your team reviews and approves before anything reaches production.
Yes. Implement a /health endpoint on the upstream service and periodically check it. If the upstream is down, return 503 Service Unavailable immediately instead of waiting for the connection to time out.
Yes. Libraries like opossum implement circuit breakers for Node.js. After a threshold of failures, the circuit opens and returns errors immediately without attempting the upstream connection.