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
Here's what each line means:
- at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:108:26): Node's DNS resolver completed the lookup but could not find any address records for the requested hostname.
- at fetchExternalData (src/services/externalApi.js:11:20): Your external API service at line 11 tried to connect to a hostname that DNS cannot resolve.
- at DataController.refresh (src/controllers/dataController.js:22:18): The controller's refresh method initiated the external API call that triggered the DNS failure.
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.
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;
}
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:
- 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)
- Verify the hostname is correct and DNS resolves from the deployment environment.
- Add retry logic with exponential backoff for DNS failures.
- Run tests to confirm retry behavior works.
- Open a pull request and wait for CI.
- 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.