Node.js ENOTFOUND
DNS lookup failed because the hostname could not be resolved.
Explanation
ENOTFOUND occurs when the DNS (Domain Name System) lookup for a hostname fails, meaning the hostname could not be resolved to an IP address. This is a common Node.js error when making HTTP requests, connecting to databases, or reaching any network service. Common causes include the hostname being misspelled, DNS server being unreachable, the domain not existing, local hosts file missing an entry, or temporary DNS resolution failures. The error includes the hostname that failed to resolve.
Common Causes
- Hostname misspelled
- DNS server unreachable
- Domain doesn't exist or expired
- Local hosts file missing entry
- Temporary DNS failure
Solution
Verify the hostname is spelled correctly. Check DNS resolution: nslookup hostname or dig hostname. Test if DNS servers are reachable. Check /etc/hosts for local entries. Try using the IP address directly to bypass DNS. Flush DNS cache: sudo dscacheutil -flushcache (Mac) or sudo systemctl restart nscd (Linux). Check network connectivity. Verify the domain exists and hasn't expired. For local development, ensure /etc/hosts or equivalent has the correct entries. Use environment variables for hostnames to avoid hardcoding.
Code Example
// ENOTFOUND when connecting to service
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'mydb.local', // DNS resolution fails!
user: 'root'
});
connection.connect((err) => {
if (err && err.code === 'ENOTFOUND') {
console.error('Cannot resolve hostname:', err.hostname);
}
});
// Fix: check DNS resolution
const dns = require('dns');
dns.lookup('mydb.local', (err, address) => {
if (err) {
console.error('DNS failed:', err.message);
} else {
console.log('Resolved to:', address);
}
});
// Use IP directly for testing
const connection = mysql.createConnection({
host: '127.0.0.1', // bypass DNS
user: 'root'
});
// Check DNS from command line
nslookup mydb.local
dig mydb.local
// Flush DNS cache (Mac)
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
Error Information
Language
javascript
Framework
nodejs
Difficulty
Beginner
Views
16
Related Errors
JavaScript
TypeError: Cannot Read Property of Undefined
The code tries to access a property or method on an undefined or null value.
DevOps
SSL Certificate Expired
The SSL/TLS certificate for the website has expired and is no longer valid.
ERR_REQUIRE_ESM
Node.js
ERR_REQUIRE_ESM
Node.js cannot require() an ES module; use import() instead.
Database
TypeORM/SQLAlchemy EntityNotFoundError
The ORM cannot find the requested entity or model in the database.