{"id":16368,"library":"gaxios","title":"gaxios HTTP Client","description":"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.","status":"active","version":"7.1.4","language":"javascript","source_language":"en","source_url":"https://github.com/googleapis/google-cloud-node-core","tags":["javascript","google","typescript"],"install":[{"cmd":"npm install gaxios","lang":"bash","label":"npm"},{"cmd":"yarn add gaxios","lang":"bash","label":"yarn"},{"cmd":"pnpm add gaxios","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary function for making HTTP requests. gaxios is an ESM-only package since v5; CommonJS `require` will lead to errors in modern Node.js.","wrong":"const { request } = require('gaxios');","symbol":"request","correct":"import { request } from 'gaxios';"},{"note":"Provides a `fetch`-compatible API (`instance.fetch`) and allows setting global defaults on the default instance.","wrong":"const { instance } = require('gaxios');","symbol":"instance","correct":"import { instance } from 'gaxios';"},{"note":"Use this class to create new Gaxios instances with custom default configurations, separate from the global `instance`.","wrong":"const Gaxios = require('gaxios').Gaxios;","symbol":"Gaxios","correct":"import { Gaxios } from 'gaxios';"}],"quickstart":{"code":"import { request, Gaxios } from 'gaxios';\n\nasync function makeGaxiosRequests() {\n  try {\n    // --- Example 1: Basic GET request using the default `request` function ---\n    console.log('--- Initiating basic GET request to Google ---');\n    const googleResponse = await request({\n      url: 'https://www.google.com/search',\n      params: { q: 'gaxios library' },\n      timeout: 10000 // 10 seconds timeout\n    });\n    console.log(`Google Search Status: ${googleResponse.status}`);\n    console.log(`Google Search Data (partial): ${googleResponse.data.substring(0, 100)}...`);\n\n    // --- Example 2: Using a custom Gaxios instance with base URL and headers ---\n    console.log('\\n--- Initiating POST request to JSONPlaceholder API ---');\n    const jsonPlaceholderClient = new Gaxios({\n      baseURL: 'https://jsonplaceholder.typicode.com',\n      headers: {\n        'Content-Type': 'application/json',\n        'User-Agent': 'MyGaxiosApp/1.0'\n      },\n      timeout: 5000\n    });\n\n    const newPostData = {\n      title: 'gaxios usage guide',\n      body: 'This is a sample post demonstrating gaxios capabilities.',\n      userId: 1\n    };\n    const postResponse = await jsonPlaceholderClient.request({\n      url: '/posts',\n      method: 'POST',\n      data: newPostData\n    });\n    console.log(`JSONPlaceholder POST Status: ${postResponse.status}`);\n    console.log(`Created Post ID: ${postResponse.data.id}, Title: ${postResponse.data.title}`);\n\n  } catch (error: any) {\n    console.error('\\nAn error occurred during gaxios request:');\n    if (error.response) {\n      console.error(`Status: ${error.response.status}, Data:`, error.response.data);\n    } else if (error.code === 'ERR_SOCKET_TIMEOUT') {\n      console.error('Request timed out.');\n    } else {\n      console.error(error.message);\n    }\n  }\n}\n\nmakeGaxiosRequests();","lang":"typescript","description":"This quickstart demonstrates basic GET and POST requests using the default `request` function and a custom `Gaxios` instance, including setting base URLs, headers, and handling timeouts and errors."},"warnings":[{"fix":"Upgrade your Node.js runtime to version 18 or higher. Alternatively, pin gaxios to a compatible version (e.g., `npm install gaxios@6`) if a Node.js upgrade is not feasible.","message":"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).","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Ensure your project uses ES Modules (`import/export`) for gaxios or configure your environment (e.g., `package.json` `\"type\": \"module\"`) to handle ESM correctly. For existing CommonJS projects, consider using dynamic `import()` or stick to an older version of gaxios if module type conversion is not an option.","message":"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.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Be mindful when setting `gaxios.defaults.headers.Authorization` or similar authentication headers. If you intend to use `google-auth-library` or other authentication mechanisms, ensure that your custom defaults do not inadvertently override them. Prefer passing authentication details per-request if defaults are broad.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"To prevent unbounded memory usage, set `maxContentLength` to a sensible byte limit (e.g., `10 * 1024 * 1024` for 10MB) in your `GaxiosOptions` if you are expecting potentially large responses.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"To receive the response body as a stream, set `responseType: 'stream'` in your `GaxiosOptions`. This will make the `res.data` property a `ReadableStream` (in browsers) or `stream.Readable` (in Node.js).","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Convert 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`.","cause":"Attempting to use `require()` to import gaxios in a CommonJS module, but gaxios is an ES Module since v5.","error":"ERR_REQUIRE_ESM: require() of ES Module .../node_modules/gaxios/build/src/index.js from ... not supported."},{"fix":"Verify 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.","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).","error":"TypeError: fetch failed"},{"fix":"Ensure 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.","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.","error":"TypeError: Agent is not a constructor"},{"fix":"Explicitly 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`.","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.","error":"Response data is not as expected (e.g., empty for JSON, or unexpected format) when sending a plain object in `data`."}],"ecosystem":"npm"}