How to prefer ipv4 for google-auth-library requests in nodejs on ubuntu 20.04

132 Views Asked by At

As of later versions of nodejs, ipv6 DNS resolution is preferred. In previous machines, I had simply disabled ipv6 for outgoing requests, but here it isn't possible because fetch() in node would fail without it.

However, some specific Google endpoints, namely https://www.googleapis.com/oauth2/v1/certs

Require ipv4 resolution, which is requested internally by OAuth2Client in google-auth-library (via Axios). The response I get from the request using ipv6 is:

Your client does not have permission to get URL <code>/oauth2/v1/certs</code> from this server.  <ins>That’s all we know.</ins>

403: Forbidden

So what solutions are there to force only these requests to prefer ipv4?

1

There are 1 best solutions below

0
emma ray On

Node provides an option to prefer IPv4 Resolution:

export NODE_OPTIONS=--dns-result-order=ipv4first

This will of course apply to all requests. If you really need to resolve other requests with IPv6 you could provide a custom agent/dispatcher to the specific request(s).

Here's an example using undici but you may be able to use https.Agent as well:

import { Agent } from 'undici';

await fetch('https://www.googleapis.com/oauth2/v1/certs', {
  dispatcher: new Agent({
    connect: {
      lookup: (hostname, options, callback) => {
        return dns.resolve4(hostname, options, callback);
      },
    },
  }),
});