npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@darcas/smart-dns-promises

v1.2.0

Published

Zero-dependency DNS resolver for Node.js with TTL-aware caching, request deduplication and stale-while-revalidate — 9 configurable providers, built for fetch and axios.

Downloads

216

Readme

SmartDns

NPM Last Update NPM Version NPM Downloads

NPM License

Buy me a coffee

A simple and efficient DNS resolver with caching and configurable DNS providers for Node.js 20 and 22 or above.

The purpose of this library is to increase the speed and performance of DNS resolution in Node.js. In environments where requests are made using libraries like fetch or axios, this can be very useful.

Features

  • DNS resolution with caching for faster lookups (zero runtime dependencies).
  • Cache entries expire according to the real DNS record TTL (configurable min/max clamp).
  • Negative caching of failed lookups to avoid hammering the resolver on down hosts.
  • In-flight deduplication: concurrent lookups for the same hostname trigger a single DNS query.
  • Optional stale-while-revalidate: expired entries are served immediately and refreshed in background.
  • Lookup statistics: hits, misses, errors, revalidations and average resolve time.
  • Supports configurable DNS providers: AdGuard, CloudFlare, Comodo, DNS.WATCH, Google, OpenDNS, Quad9, Verisign, and Yandex.
  • Allows custom result order for DNS resolutions: IPv4 first, IPv6 first, or verbatim, plus ipv4/ipv6 family selection.
  • Singleton pattern to ensure only one instance of the resolver is used.
  • Manual configuration of DNS server addresses.

Installation

To install the SmartDns in your project, run the following npm command:

npm install @darcas/smart-dns-promises

Or, if you're using yarn:

yarn add @darcas/smart-dns-promises

Usage

In environments such as APIs, it is recommended to call factory as early as possible in the application lifecycle to benefit from Node.js's DNS system configuration. See Process-wide behaviour for details.

Creating an instance

You can create or retrieve a singleton instance of the SmartDns class using the factory method. This method also allows you to configure the DNS provider, result order, and cache time-to-live (TTL).

import { SmartDns } from '@darcas/smart-dns-promises'

// Create or get the singleton instance
const dns = SmartDns.factory();

// Optionally, configure DNS provider and result order
const dnsWithConfig = SmartDns.factory('Google', 'ipv4first', 600000);

// Advanced options (4th argument)
const dnsAdvanced = SmartDns.factory('CloudFlare', 'ipv4first', undefined, {
    family: 'ipv6',     // resolve AAAA records instead of A records
    maxTtl: 3600000,    // clamp for record TTLs coming from DNS (ms)
    minTtl: 1000,       // clamp for record TTLs coming from DNS (ms)
    negativeTtl: 30000, // how long failed lookups are negatively cached (ms)
    onStats: (stats) => console.log(stats),
    swr: true,          // serve stale entries and refresh in background
});

Configuration passed to factory after the first call is ignored, because the singleton has already been created.

Process-wide behaviour

SmartDns intentionally configures Node's process-global DNS system (node:dns):

  • setProvider() and setServers() replace the resolver servers for the whole process, not just for this library.
  • The resultOrder argument of factory/the constructor calls Node's dns.setDefaultResultOrder(), which is global too.

This is by design: every HTTP client in the application — axios, fetch, or any other dependency performing DNS lookups — benefits from (and is affected by) the configured provider. For this reason, call factory() as early as possible in the application lifecycle, ideally once, so your entire Node.js software runs with a consistent and fast DNS configuration.

If multiple configurations are applied, the last one wins for the whole process.

Statistics

Every lookup updates the instance counters, available via the stats getter:

const { hits, misses, errors, revalidations, avgResolveMs } = dns.stats

Setting the DNS provider

You can set the DNS provider using the setProvider method with any DnsProvider member.

dns.setProvider('CloudFlare');

Available providers:

| Provider | Servers | |---|---| | AdGuard | 94.140.14.14, 94.140.15.15 | | CloudFlare | 1.1.1.1, 1.0.0.1 | | Comodo | 8.26.56.26, 8.20.247.20 | | DNS.WATCH | 84.200.69.80, 84.200.70.40 | | Google | 8.8.8.8, 8.8.4.4 | | OpenDNS | 208.67.222.222, 208.67.220.220 | | Quad9 | 9.9.9.9, 149.112.112.112 | | Verisign | 64.6.64.6, 64.6.65.6 | | Yandex | 77.88.8.8, 77.88.8.1 |

Setting the result Order

The result order for DNS resolutions can be configured as follows:

  • ipv4first: IPv4 addresses are preferred and returned before IPv6 addresses.
  • ipv6first: IPv6 addresses are preferred and returned before IPv4 addresses.
  • verbatim: The DNS resolution returns results in the exact order as returned by the DNS provider without preference for IPv4 or IPv6.

Resolving URLs

Use the resolver method to resolve a URL and get its IP address, hostname, and updated URL with the hostname replaced by the IP address.

const result = await dns.resolver('https://example.com');
console.log(result.address);  // Resolved IP address
console.log(result.hostname); // Original hostname
console.log(result.urlReplaced); // URL with IP address instead of hostname

Manually setting DNS servers

You can manually set DNS server IP addresses using the setServers method.

dns.setServers([
  '8.8.8.8', 
  '8.8.4.4',
]);

Error Handling

The library throws two types of errors:

  1. SmartDnsProviderError: Thrown when an unsupported DNS provider is used.
  2. SmartDnsResolverError: Thrown when there is an issue with resolving a URL (e.g., invalid URL format).

Example with Axios

This example shows how to use the package along with Axios to automatically resolve the hostname in requests to the corresponding IP address and adjust the request headers.

import { DnsProvider, SmartDns } from '@darcas/smart-dns-promises'
import { default as _axios, InternalAxiosRequestConfig } from 'axios';

const axios = _axios.create()
const dns = SmartDns.factory(DnsProvider.OpenDNS)

axios.interceptors.request.use(async (config: InternalAxiosRequestConfig): Promise<InternalAxiosRequestConfig> => {
    const {
        address,
        hostname,
        urlReplaced,
    } = await dns.resolver(config.url)

    config.headers = {
        ...config.headers ?? {},
        Host: hostname,
    } 
    config.url = urlReplaced

    return config
})

Example with fetch

The same idea with the global fetch: resolve once, request the IP directly and pass the original hostname in the Host header.

import { SmartDns } from '@darcas/smart-dns-promises'

const dns = SmartDns.factory()

async function smartFetch(url: string, init: RequestInit = {}): Promise<Response> {
    const { urlReplaced } = await dns.resolver(url)

    return fetch(urlReplaced, {
        ...init,
        headers: {
            ...init.headers,
            Host: new URL(url).hostname,
        },
    })
}

Two things to keep in mind:

  1. Replacing the hostname with the IP address means the TLS handshake is performed against the IP: this works out of the box with plain HTTP endpoints or controlled environments, but on public HTTPS endpoints the certificate is issued to the hostname, so the request will fail certificate validation. For HTTPS use cases prefer the axios example above.
  2. Thanks to the cache, subsequent requests to the same host skip the DNS lookup entirely.

Contributing

If you'd like to contribute to the project, feel free to fork it and create a pull request. Please ensure that your changes are well-tested and properly documented.

License

This project is licensed under the MIT License. See the LICENSE file for details.


Made with ❤️ by Dario Casertano (DarCas).