Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

gaxios

googleapis60.6mApache-2.06.7.1TypeScript support: included

A simple common HTTP client specifically for Google APIs and services.

google

readme

gaxios

npm version codecov Code Style: Google

An HTTP request client that provides an axios like interface over top of node-fetch.

Install

$ npm install gaxios

Example

import {request} from 'gaxios';
const res = await request({url: 'https://google.com/'});

fetch-Compatible API Example

We offer a drop-in fetch-compatible API as well.

import {instance} from 'gaxios';
const res = await instance.fetch('https://google.com/');

Setting Defaults

Gaxios supports setting default properties both on the default instance, and on additional instances. This is often useful when making many requests to the same domain with the same base settings. For example:

import {request, instance} from 'gaxios';

instance.defaults = {
  baseURL: 'https://example.com'
  headers: new Headers({
    Authorization: 'SOME_TOKEN'
  })
}

await request({url: '/data'});

Note that setting default values will take precedence over other authentication methods, i.e., application default credentials.

Request Options

interface GaxiosOptions = {
  // The url to which the request should be sent.  Required.
  url: string | URL,

  // The HTTP method to use for the request.  Defaults to `GET`.
  method: 'GET',

  // The base Url to use for the request.
  // Resolved as `new URL(url, baseURL)`
  baseURL: 'https://example.com/v1/' | URL;

  // The HTTP methods to be sent with the request.
  headers: new Headers(),

  // The data to send in the body of the request. Objects will be serialized as JSON
  // except for:
  // - `ArrayBuffer`
  // - `Blob`
  // - `Buffer` (Node.js)
  // - `DataView`
  // - `File`
  // - `FormData`
  // - `ReadableStream`
  // - `stream.Readable` (Node.js)
  // - strings
  // - `TypedArray` (e.g. `Uint8Array`, `BigInt64Array`)
  // - `URLSearchParams`
  // - all other objects where:
  //   - headers.get('Content-Type') === 'application/x-www-form-urlencoded' (as they will be serialized as `URLSearchParams`)
  //
  // Here are a few examples that would prevent setting `Content-Type: application/json` by default:
  // - data: JSON.stringify({some: 'data'}) // a `string`
  // - data: fs.readFile('./some-data.jpeg') // a `stream.Readable`
  data: {
    some: 'data'
  },

  // The max size of the http response content in bytes allowed.
  // Defaults to `0`, which is the same as unset.
  maxContentLength: 2000,

  // The query parameters that will be encoded using `URLSearchParams` and
  // appended to the url
  params: {
    querystring: 'parameters'
  },

  // The timeout for the HTTP request in milliseconds. No timeout by default.
  timeout: 60000,

  // Optional method to override making the actual HTTP request. Useful
  // for writing tests and instrumentation
  adapter?: async (options, defaultAdapter) => {
    const res = await defaultAdapter(options);
    res.data = {
      ...res.data,
      extraProperty: 'your extra property',
    };
    return res;
  };

  // The expected return type of the request.  Options are:
  // json | stream | blob | arraybuffer | text | unknown
  // Defaults to `unknown`.
  // If the `fetchImplementation` is native `fetch`, the
  // stream is a `ReadableStream`, otherwise `readable.Stream`
  responseType: 'unknown',

  // The node.js http agent to use for the request.
  agent: someHttpsAgent,

  // Custom function to determine if the response is valid based on the
  // status code.  Defaults to (>= 200 && < 300)
  validateStatus: (status: number) => true,

  /**
   * Implementation of `fetch` to use when making the API call. Will use `fetch` by default.
   */
  fetchImplementation?: typeof fetch;

  // Configuration for retrying of requests.
  retryConfig: {
    // The number of times to retry the request.  Defaults to 3.
    retry?: number;

    // The number of retries already attempted.
    currentRetryAttempt?: number;

    // The HTTP Methods that will be automatically retried.
    // Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE']
    httpMethodsToRetry?: string[];

    // The HTTP response status codes that will automatically be retried.
    // Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]]
    statusCodesToRetry?: number[][];

    // Function to invoke when a retry attempt is made.
    onRetryAttempt?: (err: GaxiosError) => Promise<void> | void;

    // Function to invoke which determines if you should retry
    shouldRetry?: (err: GaxiosError) => Promise<boolean> | boolean;

    // When there is no response, the number of retries to attempt. Defaults to 2.
    noResponseRetries?: number;

    // The amount of time to initially delay the retry, in ms.  Defaults to 100ms.
    retryDelay?: number;
  },

  // Enables default configuration for retries.
  retry: boolean,

  // Enables aborting via AbortController
  signal?: AbortSignal

  /**
   * A collection of parts to send as a `Content-Type: multipart/related` request.
   */
  multipart?: GaxiosMultipartOptions;

  /**
   * An optional proxy to use for requests.
   * Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available.
   * The `agent` option overrides this.
   *
   * @see {@link GaxiosOptions.noProxy}
   * @see {@link GaxiosOptions.agent}
   */
  proxy?: string | URL;
  /**
   * A list for excluding traffic for proxies.
   * Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules.
   *
   * - When provided a string, it is matched by
   *   - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`)
   * - When provided a URL, it is matched by the `.origin` property.
   *   - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use:
   *     - new URL('https://example.com')
   *     - new URL('https://example.com:443')
   *   - The following would be used with a proxy:
   *     - new URL('http://example.com:80')
   *     - new URL('https://example.com:8443')
   * - When provided a regular expression it is used to match the stringified URL
   *
   * @see {@link GaxiosOptions.proxy}
   */
  noProxy?: (string | URL | RegExp)[];

  /**
   * An experimental, customizable error redactor.
   *
   * Set `false` to disable.
   *
   * @remarks
   *
   * This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see:
   * - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs
   * - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets
   *
   * @experimental
   */
  errorRedactor?: typeof defaultErrorRedactor | false;
}

License

Apache-2.0

changelog

Changelog

6.7.1 (2024-08-13)

Bug Fixes

6.7.0 (2024-06-27)

Features

  • Add additional retry configuration options (#634) (cb5c833)

Bug Fixes

6.6.0 (2024-05-15)

Features

  • Add request and response interceptors (#619) (059fe77)

6.5.0 (2024-04-09)

Features

6.4.0 (2024-04-03)

Features

Bug Fixes

  • Error Redactor Case-Insensitive Matching (#613) (05e65ef)

6.3.0 (2024-02-01)

Features

6.2.0 (2024-01-31)

Features

  • Extend instanceof Support for GaxiosError (#593) (4fd1fe2)

Bug Fixes

  • Do Not Mutate Config for Redacted Retries (#597) (4d1a551)
  • Return text when content type is text/* (#579) (3cc1c76)

6.1.1 (2023-09-07)

Bug Fixes

  • Don't throw an error within a GaxiosError (#569) (035d9dd)

6.1.0 (2023-08-11)

Features

6.0.4 (2023-08-03)

Bug Fixes

  • deps: Update https-proxy-agent to 7.0.1 and fix imports and tests (#560) (5c877e2)

6.0.3 (2023-07-24)

Bug Fixes

  • Handle invalid json when Content-Type=application/json (#558) (71602eb)

6.0.2 (2023-07-20)

Bug Fixes

  • Revert attempting to convert 'text/plain', leave as data in GaxiosError (#556) (d603bde)

6.0.1 (2023-07-20)

Bug Fixes

  • Add text to responseType switch statement (#554) (899cf1f)

6.0.0 (2023-07-12)

⚠ BREAKING CHANGES

  • add status as a number to GaxiosError, change code to error code as a string (#552)
  • migrate to Node 14 (#548)
  • examine response content-type if no contentType is set (#535)

Bug Fixes

  • Add status as a number to GaxiosError, change code to error code as a string (#552) (88ba2e9)
  • Examine response content-type if no contentType is set (#535) (cd8ca7b)

Miscellaneous Chores

5.1.3 (2023-07-05)

Bug Fixes

  • Translate GaxiosError message to object regardless of return type (return data as default) (#546) (adfd570)

5.1.2 (2023-06-25)

Bug Fixes

  • Revert changes to error handling due to downstream breakage (#544) (64fbf07)

5.1.1 (2023-06-23)

Bug Fixes

  • Translate GaxiosError message to object regardless of return type (#537) (563c653)

5.1.0 (2023-03-06)

Features

5.0.2 (2022-09-09)

Bug Fixes

5.0.1 (2022-07-04)

Bug Fixes

  • types: loosen AbortSignal type (5a379ca)

5.0.0 (2022-04-20)

⚠ BREAKING CHANGES

  • drop node 10 from engines list, update typescript to 4.6.3 (#477)

Features

  • handling missing process global (c30395b)

Build System

  • drop node 10 from engines list, update typescript to 4.6.3 (#477) (a926962)

4.3.3 (2022-04-08)

Bug Fixes

4.3.2 (2021-09-14)

Bug Fixes

  • address codeql warning with hostname matches (#415) (5a4d060)

4.3.1 (2021-09-02)

Bug Fixes

  • build: switch primary branch to main (#427) (819219e)

4.3.0 (2021-05-26)

Features

  • allow cert and key to be provided for mTLS (#399) (d74ab91)

4.2.1 (2021-04-20)

Bug Fixes

  • deps: upgrade webpack and karma-webpack (#379) (75c9013)

4.2.0 (2021-03-01)

Features

  • handle application/x-www-form-urlencoded/Buffer (#374) (ce21e9c)

4.1.0 (2020-12-08)

Features

4.0.1 (2020-10-27)

Bug Fixes

  • prevent bonus ? with empty qs params (#357) (b155f76)

4.0.0 (2020-10-21)

⚠ BREAKING CHANGES

  • parameters in url and parameters provided via params will now be combined.

Bug Fixes

  • drop requirement on URL/combine url and params (#338) (e166bc6)

3.2.0 (2020-09-14)

Features

  • add initial retry delay, and set default to 100ms (#336) (870326b)

3.1.0 (2020-07-30)

Features

  • pass default adapter to adapter option (#319) (cf06bd9)

3.0.4 (2020-07-09)

Bug Fixes

3.0.3 (2020-04-20)

Bug Fixes

3.0.2 (2020-03-24)

Bug Fixes

  • continue replacing application/x-www-form-urlencoded with application/json (#263) (dca176d)

3.0.1 (2020-03-23)

Bug Fixes

  • allow an alternate JSON content-type to be set (#257) (698a29f)

3.0.0 (2020-03-19)

⚠ BREAKING CHANGES

  • deps: TypeScript introduced breaking changes in generated code in 3.7.x
  • drop Node 8 from engines field (#254)

Features

2.3.2 (2020-02-28)

Bug Fixes

2.3.1 (2020-02-13)

Bug Fixes

  • deps: update dependency https-proxy-agent to v5 (#233) (56de0a8)

2.3.0 (2020-01-31)

Features

  • add promise support for onRetryAttempt and shouldRetry (#223) (061afa3)

2.2.2 (2020-01-08)

Bug Fixes

  • build: add publication configuration (#218) (43e581f)

2.2.1 (2020-01-04)

Bug Fixes

2.2.0 (2019-12-05)

Features

  • populate GaxiosResponse with raw response information (res.url) (#189) (53a7f54)

Bug Fixes

  • don't retry a request that is aborted intentionally (#190) (ba9777b)
  • deps: pin TypeScript below 3.7.0 (5373f07)

2.1.1 (2019-11-15)

Bug Fixes

  • docs: snippets are now replaced in jsdoc comments (#183) (8dd1324)

2.1.0 (2019-10-09)

Bug Fixes

  • deps: update dependency https-proxy-agent to v3 (#172) (4a38f35)

Features

  • TypeScript: agent can now be passed as builder method, rather than agent instance (c84ddd6)

2.0.3 (2019-09-11)

Bug Fixes

2.0.2 (2019-07-23)

Bug Fixes