Node.js DNS Module
Node.js DNS Module: Resolving Domains and DNS Records
The node:dns/promises module lets Node.js scripts look up IP addresses for domain names and inspect MX, TXT, CNAME, and A/AAAA records. Backend services use DNS lookups for email domain verification, service discovery, and validating external webhook URLs against local IP spoofing.
dns.lookup() vs dns.resolve4()
Node.js separates DNS resolution into two distinct families that behave very differently under load:
dns.lookup(hostname): Calls the operating system's resolver (reading/etc/hostsand OS DNS cache) inside Node'slibuvthread pool. It matches whatfetch()andcurlsee.dns.resolve4(hostname)/dns.resolveMx(hostname): Sends live DNS packets over the network directly to DNS servers without touching/etc/hostsor consuminglibuvthreads.
import dns from 'node:dns/promises';
async function inspectDomain(domain) {
const addresses = await dns.lookup(domain, { all: true });
const mxRecords = await dns.resolveMx(domain);
console.log('OS Lookup IPs:', addresses);
console.log('Mail Servers:', mxRecords.sort((a, b) => a.priority - b.priority));
}
inspectDomain('example.com').catch((err) => console.error('DNS error:', err.message));
Guarding Webhooks Against SSRF via DNS Inspection
When your API accepts user-supplied webhook URLs, checking that the URL string says https://evil.example.com is not enough—the domain's DNS A record could point to 127.0.0.1 or 169.254.169.254 (cloud metadata). Resolving the IP first and rejecting private/loopback IP ranges closes that attack vector.
Common Mistakes to Avoid
- Flooding
dns.lookup()without realizing it uses the 4-threadlibuvpool: Hundreds of slowdns.lookup()calls can stall file-system operations sharing the same thread pool. Usedns.resolve4()when querying external DNS records in bulk. - Calling
dns.resolve('localhost'):dns.resolve*skips/etc/hostsand fails on local aliases likelocalhostor Docker container names. Usedns.lookup()when resolving local hostnames. - Assuming every domain has IPv6 (
AAAA) records: Wrapdns.resolve6()intry / catchbecause many domains only publish IPv4Arecords (ENODATA).
Frequently Asked Questions
Why does dns.resolveMx() return a priority number?
Lower priority numbers indicate the preferred mail server; mail clients try the lowest priority host first before falling back to higher numbers.
Does Node.js cache dns.lookup() results forever?
No. Node.js delegates dns.lookup() directly to the host OS resolver, whose caching behavior depends on Linux nscd/systemd-resolved, macOS, or Windows DNS cache settings.
How do I inspect SPF or domain-verification TXT records?
Call await dns.resolveTxt('example.com'), which returns an array of string arrays representing each DNS TXT record.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.