All Products
Search
Document Center

HTTPDNS:Best practices for using HTTPDNS with Alibaba Cloud OSS SDK for Node.js

Last Updated:Sep 11, 2025

This topic describes how to integrate HTTPDNS with the Alibaba Cloud OSS SDK in a Node.js application.

1. Background

Alibaba Cloud Object Storage Service (OSS) is a general-purpose cloud storage service that allows developers to easily store and access files, such as profile pictures, images, audio, and video, in various applications by integrating the OSS SDK for Node.js.

To improve the stability and speed of file transfers, you can combine the HTTPDNS SDK with the OSS SDK for Node.js to parse OSS domain names. This combination provides effective anti-hijacking and accelerates DNS parsing, which optimizes the network experience when your application accesses OSS.

2. Integration steps

To integrate HTTPDNS with the OSS SDK in Node.js, follow these three core steps:

  1. Install and initialize the HTTPDNS SDK

  2. Create a custom agent that integrates HTTPDNS

  3. Initialize the OSS client with the custom agent

2.1 Install dependencies

First, install the required dependency packages:

Download the Node.js SDK and integration examples: httpdns-nodejs-sdk.zip.

npm install ali-oss

Version requirements:

  • ali-oss: >= 4.0.0

  • Node.js: >= 12.0.0

  • httpdns-nodejs-sdk: >= 1.0.0

2.2 Initialize the HTTPDNS SDK

Initialize the HTTPDNS SDK when the application starts:

const { createClient } = require('httpdns-nodejs-sdk');

// Initialize the HTTPDNS client
const httpdnsClient = createClient({
  accountId: 'your-account-id',
  secretKey: 'your-secret-key', // Optional. Used for authenticated parsing.
});

2.3 Create a custom agent that integrates HTTPDNS

Create a custom HTTPS agent that integrates the HTTPDNS parsing capability:

const https = require('https');
const dns = require('dns');

/**
 * Creates a custom DNS lookup function
 */
function createHTTPDNSLookup(httpdnsClient) {
  return (hostname, options, callback) => {
    // Standardize parameters
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }
  
    // Make sure the callback exists
    if (typeof callback !== 'function') {
      throw new Error('callback must be a function');
    }
  
    // Use HTTPDNS to parse the domain name
    const result = this.httpdnsClient.getHttpDnsResultForHostSyncNonBlocking(hostname);
  
    if (result && result.success) {
      const hasIPv4 = result.ipv4 && result.ipv4.length > 0;
      const hasIPv6 = result.ipv6 && result.ipv6.length > 0;
  
      if (hasIPv4 || hasIPv6) {
        if (options && options.all) {
          // Return all IP addresses
          const addresses = [
            ...(hasIPv4 ? result.ipv4.map(ip => ({ address: ip, family: 4 })) : []),
            ...(hasIPv6 ? result.ipv6.map(ip => ({ address: ip, family: 6 })) : [])
          ];
          console.log(`[DNS Lookup] HTTPDNS parsing successful: ${hostname} -> Returning all IP addresses (${addresses.length})`);
          callback(null, addresses);
        } else {
          // Prioritize IPv4, then IPv6
          if (hasIPv4) {
            console.log(`[DNS Lookup] HTTPDNS parsing successful: ${hostname} -> ${result.ipv4[0]} (IPv4)`);
            callback(null, result.ipv4[0], 4);
          } else {
            console.log(`[DNS Lookup] HTTPDNS parsing successful: ${hostname} -> ${result.ipv6[0]} (IPv6)`);
            callback(null, result.ipv6[0], 6);
          }
        }
        return;
      }
    }
  
    console.log(`[DNS Lookup] No available IP from HTTPDNS. Falling back to system DNS for: ${hostname}`);
    dns.lookup(hostname, options, callback);
  };
}

/**
 * Creates an HTTPS agent that integrates HTTPDNS
 */
function createHTTPDNSAgent(httpdnsClient) {
  return new https.Agent({
    lookup: createHTTPDNSLookup(httpdnsClient),
    keepAlive: true,
    maxSockets: 10,
  });
}

2.4 Initialize the OSS client

Initialize the OSS client with the custom agent:

const OSS = require('ali-oss');

/**
 * Creates an OSS client that integrates HTTPDNS
 */
function createOSSClient(httpdnsClient, ossConfig) {
  // Create a custom agent
  const httpsAgent = createHTTPDNSAgent(httpdnsClient);
  
  // Create an OSS client and pass in the custom agent
  const ossClient = new OSS({
    region: ossConfig.region,
    accessKeyId: ossConfig.accessKeyId,
    accessKeySecret: ossConfig.accessKeySecret,
    bucket: ossConfig.bucket,
    httpsAgent: httpsAgent // Core: Pass in the agent that integrates HTTPDNS
  });

  console.log('OSS client created and integrated with HTTPDNS');
  return ossClient;
}

// Example usage
const ossConfig = {
  region: 'oss-cn-hangzhou',
  accessKeyId: 'your-access-key-id',
  accessKeySecret: 'your-access-key-secret',
  bucket: 'your-bucket-name'
};

const ossClient = createOSSClient(httpdnsClient, ossConfig);

3. Summary

By combining HTTPDNS with the OSS SDK for Node.js, you can effectively prevent DNS hijacking and accelerate file transfers, which improves access stability and security. The core of this implementation is to configure a custom https.Agent with HTTPDNS parsing logic for OSS.

Key points:

  • Initialization order: Initialize HTTPDNS before you initialize the OSS client.

  • Fallback mechanism: If HTTPDNS parsing fails, the system falls back to the system DNS.

By following the best practices in this topic, you can achieve high-performance and high-availability OSS access in your Node.js applications.

For detailed information on the usage and API of the HTTPDNS SDK for Node.js, see Best practices for Node.js.