How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Node.js · JavaScript

Fix Error: getaddrinfo ENOTFOUND api.example.com in Node.js

This error means the DNS resolver could not find an IP address for the given hostname. Common causes include typos in the hostname, DNS server unavailability, or network configuration issues inside containers. Fix it by verifying the hostname, checking DNS configuration, and adding retry logic for transient failures.

Reading the Stack Trace

Error: getaddrinfo ENOTFOUND api.example.com at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:108:26) at GetAddrInfoReqWrap.callbackTrampoline (node:internal/async_hooks:130:17) at ClientRequest.emit (node:events:513:28) at TLSSocket.socketErrorListener (node:_http_client:502:9) at TLSSocket.emit (node:events:513:28) at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) at fetchExternalData (src/services/externalApi.js:11:20) at DataController.refresh (src/controllers/dataController.js:22:18)

Here's what each line means:

Common Causes

1. Typo in hostname

The URL contains a misspelled hostname that does not exist in DNS.

const API_URL = 'https://api.exmple.com/v1/data'; // Typo: exmple

2. DNS not available in container

The Docker container does not have DNS configured correctly or cannot reach the DNS server.

// docker-compose.yml uses custom network without DNS config
const response = await fetch('https://api.example.com/data');

3. Transient DNS failure

The DNS server is temporarily unreachable due to network issues, but the code has no retry logic.

async function fetchData() {
  return await axios.get(API_URL); // No retry on DNS failure
}

The Fix

Add retry logic specifically for ENOTFOUND errors to handle transient DNS failures. Include a request timeout so the call does not hang indefinitely. The API URL comes from an environment variable so it can be configured per environment.

Before (broken)
const axios = require('axios');

const API_URL = process.env.API_URL || 'https://api.example.com';

async function fetchExternalData() {
  const response = await axios.get(`${API_URL}/v1/data`);
  return response.data;
}
After (fixed)
const axios = require('axios');
const dns = require('dns').promises;

const API_URL = process.env.API_URL || 'https://api.example.com';
const MAX_RETRIES = 3;

async function fetchExternalData(retries = MAX_RETRIES) {
  try {
    const response = await axios.get(`${API_URL}/v1/data`, {
      timeout: 10000,
    });
    return response.data;
  } catch (err) {
    if (err.code === 'ENOTFOUND' && retries > 0) {
      console.warn(`DNS lookup failed for ${API_URL}, retrying (${retries} left)...`);
      await new Promise((r) => setTimeout(r, 1000));
      return fetchExternalData(retries - 1);
    }
    throw err;
  }
}

Testing the Fix

const axios = require('axios');
const { fetchExternalData } = require('./externalApi');

jest.mock('axios');

describe('fetchExternalData', () => {
  it('returns data on successful request', async () => {
    axios.get.mockResolvedValue({ data: { items: [] } });
    const data = await fetchExternalData();
    expect(data.items).toEqual([]);
  });

  it('retries on ENOTFOUND and succeeds', async () => {
    const dnsError = new Error('getaddrinfo ENOTFOUND');
    dnsError.code = 'ENOTFOUND';
    axios.get
      .mockRejectedValueOnce(dnsError)
      .mockResolvedValueOnce({ data: { items: [1] } });
    const data = await fetchExternalData(2);
    expect(data.items).toEqual([1]);
    expect(axios.get).toHaveBeenCalledTimes(2);
  });

  it('throws after all retries are exhausted', async () => {
    const dnsError = new Error('getaddrinfo ENOTFOUND');
    dnsError.code = 'ENOTFOUND';
    axios.get.mockRejectedValue(dnsError);
    await expect(fetchExternalData(1)).rejects.toThrow('ENOTFOUND');
  });
});

Run your tests:

npm test

Pushing Through CI/CD

git checkout -b fix/nodejs-dns-lookup-error,git add src/services/externalApi.js src/services/__tests__/externalApi.test.js,git commit -m "fix: add retry logic for DNS lookup failures",git push origin fix/nodejs-dns-lookup-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: npm test -- --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. Verify the hostname is correct and DNS resolves from the deployment environment.
  2. Add retry logic with exponential backoff for DNS failures.
  3. Run tests to confirm retry behavior works.
  4. Open a pull request and wait for CI.
  5. Merge and verify DNS resolution works in staging.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other modules are affected before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

Run 'docker exec <container> nslookup hostname' or 'cat /etc/resolv.conf' inside the container to check DNS configuration. You may need to add dns entries to your docker-compose.yml.

Node.js does not cache DNS lookups by default. For high-throughput services, consider using the cacheable-lookup package or configuring dns.setDefaultResultOrder to optimize resolution.