How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Express · JavaScript

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

Error: connect ECONNREFUSED 127.0.0.1:5000 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1595:16) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 5000 } at ClientRequest.<anonymous> (/app/node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js:172:24) at ClientRequest.emit (node:events:518:28) at Socket.socketErrorListener (node:_http_client:500:9) at Socket.emit (node:events:518:28) at emitErrorNT (node:internal/streams/destroy:169:8) at emitErrorCloseNT (node:internal/streams/destroy:128:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Here's what each line means:

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.

Before (broken)
const { createProxyMiddleware } = require('http-proxy-middleware');

app.use('/api', createProxyMiddleware({
  target: 'http://localhost:5000',
  changeOrigin: true
}));
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run the test suite locally to confirm proxy errors return 502 instead of crashing.
  2. Open a pull request with the proxy error handling changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.