Superagent HTTP Client

10.3.0 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `superagent` with `async/await` for both GET and POST requests, including proper error handling for network and API responses.

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);

view raw JSON →