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 🙏

© 2024 – Pkg Stats / Ryan Hefner

google-dns-api

v1.0.2

Published

Client for the Google JSON DNS over HTTPS API.

Downloads

28

Readme

CI status License npm version

google-dns-api

A TypeScript wrapper for Google's DNS over HTTPS (DoH) JSON API.

This package allows you to easily perform DNS queries (e.g. A, AAAA, MX, etc.) directly from your web application without the need for a backend server or browser extensions.

Features

  • TypeScript support: Fully typed API, offering great autocompletion and type safety when using modern IDEs.
  • Simple to use: Perform DNS queries with just a few lines of code. It also offers nicer and clearer wrappers around the Google Request and Response objects.
  • No backend required: Directly query Google's DNS API from the browser.
  • Supports multiple DNS record types: Query for A, AAAA, MX, TXT, CNAME, and more (all 32 record types supported by Google).

Installation

You can install the package via npm:

npm install google-dns-api

Or using Bun:

bun add google-dns-api

Usage

Here’s a simple example of how to use the google-dns-api package to perform DNS queries.

Use the query() method

import { query, RecordType } from 'google-dns-api';


query('example.com', RecordType.NS)
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

and the response would be:

{
  status: 0,
  isTruncated: false,
  isDNSSECValidated: true,
  isCheckingDisabled: false,
  question: [ { name: 'example.com.', type: 'NS' } ],
  answer: [
    {
      name: 'example.com.',
      type: 'NS',
      TTL: 4399,
      data: 'b.iana-servers.net.'
    },
    {
      name: 'example.com.',
      type: 'NS',
      TTL: 4399,
      data: 'a.iana-servers.net.'
    }
  ]
}

Response

The Response type is a convenience wrapper:

type Response = {
  status: number;
  isTruncated: boolean;
  isDNSSECValidated: boolean;
  isCheckingDisabled: boolean;
  question: Question[];
  answer?: Answer[];
  comment?: string;
};

type Question = {
  name: string;
  type: string;
};

type Answer = {
  name: string;
  type: string;
  TTL?: number;
  data: string;
};

Helpers

There are helpers for common RecordTypes (A, TXT, MX).

import { queryA, queryMX, queryTXT } from 'google-dns-api';

queryA('example.com')
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

queryMX('example.com')
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

queryTXT('example.com')
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

Options

The query function also supports being passed in an Options object:

type Options = {
  client?: Client;
  disableChecking?: boolean;
  contentType?: ContentType;
  DNSSEC?: boolean;
  EDNSClientSubnet?: string;
  randomPadding?: string;
};

Information about each option (which can be read fully on the Google API docs: link).

client

default: omitted

Use this option to pass in a client (more on clients below). This is useful if you have set a custom logger on the client.

disableChecking

default: false

If true, disables DNSSEC validation.

contentType

default: "application/x-javascript"

If set to application/x-javascript, you will have the response in JSON format. Use application/dns-message to receive a binary DNS message in the response HTTP body instead of JSON text (Note: this is not currently supported via the query or Client).

DNSSEC

default: false

If true, the response will include DNSSEC records (RRSIG, NSEC, NSEC3).

EDNSClientSubnet

default: omitted

Format is an IP address with a subnet mask. Examples: 1.2.3.4/24, 2001:700:300::/48.

If you are using DNS-over-HTTPS because of privacy concerns, and do not want any part of your IP address to be sent to authoritative name servers for geographic location accuracy, use edns_client_subnet=0.0.0.0/0. Google Public DNS normally sends approximate network information (usually zeroing out the last part of your IPv4 address).

randomPadding

The value of this parameter is ignored. Example: XmkMw~o_mgP2pf.gpw-Oi5dK.

API clients concerned about possible side-channel privacy attacks using the packet sizes of HTTPS GET requests can use this to make all requests exactly the same size by padding requests with random data. To prevent misinterpretation of the URL, restrict the padding characters to the unreserved URL characters: upper- and lower-case letters, digits, hyphen, period, underscore and tilde.

Client

There is also a Client class, which supports passing in a Logger as well as setting showRawResponse to not return this package's wrapper Response but Google's.

The constructor has the signature:

constructor(showRawResponse: boolean = false, logger?: Logger)

Loggers implement the interface:

type LogFunc = (...params: Value[]) => void;

interface Logger {
  log: LogFunc;
  error: LogFunc;
}

A few convenience loggers are provided:

  • NoopLogger: ignores all log/error calls
  • ConsoleLogger: passes log calls to console.log and error calls to console.error
  • FnLogger: takes in a function which will be called on every log and error call.

Usage of FnLogger


type Which = "log" | "error";

const myFunc = (which: Which, ...params: Value[]) => {
  // do something with this 
}

const logger = new FnLogger(fn);
logger.log("something"); // will call myFunc("log", "something")

Using the Client

The client has a method do with the signature:

async do(req: Request): Promise<Response | google.Response>

The Request is the package's wrapper around Google's request:

type Request = {
  name: string;
  type: RecordType;
  disableChecking?: boolean;
  contentType?: "application/x-javascript" | "application/dns-message";
  DNSSEC?: boolean;
  EDNSClientSubnet?: string;
  randomPadding?: string;
}

Contributing

Contributions are welcome! Please open an issue or submit a pull request to suggest improvements or add new features.

Acknowledgements

This project uses the Google DNS-over-HTTPS API.


Happy querying! 🎉