AskHandle Blog
ECONNREFUSED in Node.js: Fix Your Connection Issues

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.
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:
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:
1# For MongoDB
2ps aux | grep mongod
3
4# For Node.js servers
5lsof -i :30002. Verify Connection Details
Double-check your connection configuration:
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:
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:
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
- Always include timeout settings in your connection configs
- Set up health checks for your services
- Log connection errors properly for debugging
- Use environment variables for connection details
- Implement circuit breakers for external services
Testing for ECONNREFUSED
Create tests to verify your error handling:
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.