gaxios HTTP Client
gaxios is an HTTP client library meticulously designed for seamless integration with Google APIs and services, providing a familiar `axios`-like interface built on top of `node-fetch`. It facilitates robust HTTP request management in both Node.js and browser environments. The current stable version, 7.1.4, is actively maintained as part of the broader `google-cloud-node-core` monorepo. This integration means its release cadence is often synchronized with updates to other Google client libraries, leading to frequent releases driven by bug fixes, dependency updates, and feature enhancements within the Google ecosystem. Key differentiators include its explicit optimization for Google's API patterns, a developer-friendly `axios`-like API, and an alternative `fetch`-compatible API for wider browser and modern Node.js compatibility. The package ships with comprehensive TypeScript types, ensuring a strong development experience in TypeScript projects. It officially supports Node.js environments version 18 and above.
Common errors
-
ERR_REQUIRE_ESM: require() of ES Module .../node_modules/gaxios/build/src/index.js from ... not supported.
cause Attempting to use `require()` to import gaxios in a CommonJS module, but gaxios is an ES Module since v5.fixConvert your module to ES Module syntax using `import { symbol } from 'gaxios';` and ensure your `package.json` has `"type": "module"` or your file ends with `.mjs`. -
TypeError: fetch failed
cause This generic error indicates a fundamental network issue, such as a DNS resolution failure, network connectivity loss, firewall blocking the request, or an invalid URL scheme (e.g., `http` where `https` is expected or vice-versa).fixVerify network connectivity, check for proxy configurations, ensure the target URL is correct and accessible, and confirm that firewalls are not blocking outbound connections from your application. -
TypeError: Agent is not a constructor
cause This error can occur if a proxy agent library (like `http-proxy-agent` or `https-proxy-agent`), used internally or explicitly, changes its default export from a constructor to an object with named exports, leading to incorrect instantiation.fixEnsure all related dependencies (gaxios, teeny-request, proxy agents) are updated to their latest compatible versions, as this often indicates an incompatibility between versions of underlying networking libraries. If explicitly using an agent, check its documentation for updated instantiation patterns. -
Response data is not as expected (e.g., empty for JSON, or unexpected format) when sending a plain object in `data`.
cause By default, gaxios attempts to infer the `Content-Type` header when `data` is a plain object, usually setting it to `application/json`. If your API expects a different content type (e.g., `application/x-www-form-urlencoded`) but `data` is an object, gaxios might serialize it as JSON incorrectly.fixExplicitly set the `Content-Type` header in your `GaxiosOptions` (e.g., `headers: { 'Content-Type': 'application/x-www-form-urlencoded' }`) when the target API expects a format other than JSON for object payloads. For `URLSearchParams`, pass an instance of `URLSearchParams` to `data`.
Warnings
- breaking gaxios v7 and above require Node.js 18 or newer. Projects running on older Node.js versions (e.g., 16) must either upgrade their Node.js runtime or use an earlier version of gaxios (e.g., v6).
- breaking gaxios transitioned to an ESM-only package starting from v5. Attempting to use `require()` for imports in a CommonJS module will result in `ERR_REQUIRE_ESM` errors.
- gotcha The `gaxios.defaults` property, when set on a `Gaxios` instance, will take precedence over other authentication methods, including application default credentials. This can lead to unexpected authentication failures if not managed carefully, especially when working with Google APIs.
- gotcha The `maxContentLength` option defaults to `0`, which signifies no limit on the response content size, not a zero-byte limit. This can lead to excessive memory consumption for very large responses if not explicitly configured.
- gotcha By default, gaxios automatically processes the response body (e.g., JSON, text). If you need to handle the raw response stream (e.g., for large file downloads), this auto-processing needs to be disabled.
Install
-
npm install gaxios -
yarn add gaxios -
pnpm add gaxios
Imports
- request
const { request } = require('gaxios');import { request } from 'gaxios'; - instance
const { instance } = require('gaxios');import { instance } from 'gaxios'; - Gaxios
const Gaxios = require('gaxios').Gaxios;import { Gaxios } from 'gaxios';
Quickstart
import { request, Gaxios } from 'gaxios';
async function makeGaxiosRequests() {
try {
// --- Example 1: Basic GET request using the default `request` function ---
console.log('--- Initiating basic GET request to Google ---');
const googleResponse = await request({
url: 'https://www.google.com/search',
params: { q: 'gaxios library' },
timeout: 10000 // 10 seconds timeout
});
console.log(`Google Search Status: ${googleResponse.status}`);
console.log(`Google Search Data (partial): ${googleResponse.data.substring(0, 100)}...`);
// --- Example 2: Using a custom Gaxios instance with base URL and headers ---
console.log('\n--- Initiating POST request to JSONPlaceholder API ---');
const jsonPlaceholderClient = new Gaxios({
baseURL: 'https://jsonplaceholder.typicode.com',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'MyGaxiosApp/1.0'
},
timeout: 5000
});
const newPostData = {
title: 'gaxios usage guide',
body: 'This is a sample post demonstrating gaxios capabilities.',
userId: 1
};
const postResponse = await jsonPlaceholderClient.request({
url: '/posts',
method: 'POST',
data: newPostData
});
console.log(`JSONPlaceholder POST Status: ${postResponse.status}`);
console.log(`Created Post ID: ${postResponse.data.id}, Title: ${postResponse.data.title}`);
} catch (error: any) {
console.error('\nAn error occurred during gaxios request:');
if (error.response) {
console.error(`Status: ${error.response.status}, Data:`, error.response.data);
} else if (error.code === 'ERR_SOCKET_TIMEOUT') {
console.error('Request timed out.');
} else {
console.error(error.message);
}
}
}
makeGaxiosRequests();