AskHandle

AskHandle Blog

ECONNREFUSED in Node.js: Fix Your Connection Issues

December 25, 2025Jessy Chan3 min read

ECONNREFUSED in Node.js: Fix Your Connection Issues

Network errors can make any developer's life difficult, and ECONNREFUSED is one of those common error messages you might see when working with Node.js applications. Let's explore what this error means and how to fix it effectively.

What is ECONNREFUSED?

ECONNREFUSED is a connection error that occurs when your Node.js application tries to connect to a server or service that's not accepting the connection. This typically happens when:

  • The target server is not running
  • You're trying to connect to the wrong port
  • A firewall is blocking the connection
  • The service you're trying to reach has crashed

Common Scenarios

Local Development Issues

When working on your local machine, ECONNREFUSED often shows up if you forget to start your server or database. For example, if your Node.js application tries to connect to MongoDB at localhost:27017, but MongoDB isn't running, you'll get this error.

javascript
1MongoClient.connect('mongodb://localhost:27017', (err) => {
2  if (err) {
3    console.error('Failed to connect:', err);
4    // Will show ECONNREFUSED error
5  }
6});

API Connections

Making requests to external APIs can also trigger this error if the endpoint is down or unreachable. Here's what it might look like when using axios:

javascript
1axios.get('http://api.example.com')
2  .catch(error => {
3    if (error.code === 'ECONNREFUSED') {
4      console.log('Service is not available');
5    }
6  });

How to Fix ECONNREFUSED

1. Check Your Service Status

First, make sure the service you're trying to connect to is actually running. For local services, you can use commands like:

bash
1# For MongoDB
2ps aux | grep mongod
3
4# For Node.js servers
5lsof -i :3000

2. Verify Connection Details

Double-check your connection configuration:

javascript
1// Wrong port
2const wrongConfig = {
3  host: 'localhost',
4  port: 3001  // Oops, should be 3000
5}
6
7// Correct port
8const correctConfig = {
9  host: 'localhost',
10  port: 3000
11}

3. Implement Retry Logic

Add retry mechanisms to handle temporary connection issues:

javascript
1const retry = require('retry');
2
3function connectWithRetry() {
4  const operation = retry.operation({
5    retries: 5,
6    factor: 2,
7    minTimeout: 1000,
8  });
9
10  operation.attempt(async (currentAttempt) => {
11    try {
12      await connectToService();
13    } catch (error) {
14      if (error.code === 'ECONNREFUSED') {
15        operation.retry(error);
16      }
17    }
18  });
19}

4. Use Error Boundaries

Create proper error handling mechanisms:

javascript
1process.on('uncaughtException', (error) => {
2  if (error.code === 'ECONNREFUSED') {
3    console.log('Lost connection. Starting reconnection process...');
4    // Add reconnection logic here
5  }
6});

Best Practices

  1. Always include timeout settings in your connection configs
  2. Set up health checks for your services
  3. Log connection errors properly for debugging
  4. Use environment variables for connection details
  5. Implement circuit breakers for external services

Testing for ECONNREFUSED

Create tests to verify your error handling:

javascript
1describe('Connection handling', () => {
2  it('should handle ECONNREFUSED gracefully', async () => {
3    // Stop the service first
4    await stopService();
5    
6    try {
7      await connectToService();
8    } catch (error) {
9      expect(error.code).to.equal('ECONNREFUSED');
10    }
11  });
12});

Network errors like ECONNREFUSED are common in distributed systems. Building robust applications means preparing for these failures and handling them gracefully. With proper error handling, monitoring, and retry mechanisms, you can create more reliable Node.js applications that recover from connection issues automatically.