Superagent HTTP Client
Superagent is a lightweight, progressive HTTP request client library designed for both Node.js and browser environments, offering a consistent and fluent API. It is currently at stable version 10.3.0 and exhibits an active development cadence, with frequent patch and minor releases addressing bugs, dependency updates, and minor enhancements. Its key differentiators include a minimal footprint for browser use (approx. 50KB minified and gzipped), a highly chainable request builder API, and robust support for various HTTP features like redirects, retries, and multipart requests. Superagent supports traditional callback-based APIs, Promises for `.then().catch()` patterns, and `async/await` for modern JavaScript concurrency. It serves as a popular alternative to `axios`, `fetch` API (especially in environments requiring broad browser compatibility), or `node-fetch`, providing a unified interface across different JavaScript runtimes.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use CommonJS `require()` syntax in an ES Module context (e.g., a `.mjs` file or a project with `"type": "module"` in `package.json`).fixChange `const superagent = require('superagent');` to `import superagent from 'superagent';`. -
TypeError: (0 , hexoid_1.hexoid) is not a function
cause A dependency issue with `hexoid` when bundled with Webpack, affecting older versions of Superagent.fixUpdate `superagent` to version 10.1.1 or newer to resolve this internal dependency conflict. -
UnhandledPromiseRejectionWarning: Unhandled promise rejection.
cause A `superagent` request using promises (`.then()`) or `async/await` failed, and no `.catch()` handler or `try...catch` block was provided to handle the error.fixEnsure all `superagent` promise chains include a `.catch(errorCallback)` and all `async/await` calls are wrapped in `try...catch` blocks.
Warnings
- breaking Superagent v10.x requires Node.js version 14.18.0 or higher. Running on older Node.js versions will result in compatibility issues or failures.
- gotcha When using `superagent` in a browser environment, especially targeting older browsers, you may need to include polyfills for modern JavaScript features like `WeakRef` and `BigInt`.
- gotcha Mixing CommonJS `require()` with ES Module `import` syntax can lead to 'require is not defined' errors in modern Node.js environments configured for ESM or in bundlers. Superagent is primarily consumed as a default export.
- gotcha Forgetting to add a `.catch()` block or `.end((err, res) => ...)` callback to a `superagent` promise chain can lead to unhandled promise rejections, which crash Node.js processes or result in silent failures in browsers.
- gotcha Versions of `superagent` prior to v10.1.1 might encounter a 'hexoid is not a function' error when bundled with Webpack, due to a dependency issue.
Install
-
npm install superagent -
yarn add superagent -
pnpm add superagent
Imports
- superagent
import { superagent } from 'superagent';import superagent from 'superagent';
- superagent
const superagent = require('superagent'); - superagent
window.superagent.get('/api/data').end(...);
Quickstart
import superagent from 'superagent';
const API_BASE = 'https://jsonplaceholder.typicode.com'; // Example API
async function fetchUserData(userId) {
try {
// Make a GET request to an example API
const userResponse = await superagent
.get(`${API_BASE}/users/${userId}`)
.set('Accept', 'application/json');
console.log(`Fetched user ${userId}:`, userResponse.body);
// Make a POST request with JSON payload
const postResponse = await superagent
.post(`${API_BASE}/posts`)
.send({ title: 'foo', body: 'bar', userId: userId })
.set('Content-Type', 'application/json')
.set('Accept', 'application/json');
console.log('Created post:', postResponse.body);
} catch (err) {
if (err.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error('API Error:', err.response.status, err.response.body);
} else if (err.request) {
// The request was made but no response was received
console.error('Network Error:', err.request);
} else {
// Something happened in setting up the request that triggered an Error
console.error('Request Setup Error:', err.message);
}
}
}
fetchUserData(1);