superagent の使い方

elegant & feature rich browser / node HTTP with a fluent API

v10.3.016.6M/週MITHTTPクライアント
AI生成コンテンツ

この記事はAIによって生成されました。内容の正確性は保証されません。最新の情報は公式ドキュメントをご確認ください。

superagent の使い方 — ブラウザ/Node.js 両対応のHTTPクライアント

一言でいうと

superagent は、ブラウザと Node.js の両方で動作する軽量なHTTPクライアントライブラリです。メソッドチェーンによる流暢(fluent)なAPIが特徴で、Promise/async-await にも対応しています。

どんな時に使う?

  • REST APIとの通信 — JSON の送受信、ヘッダー設定、クエリパラメータの組み立てを直感的なチェーンAPIで行いたいとき
  • ファイルアップロード — マルチパートフォームデータの送信を簡潔に書きたいとき
  • テスト環境でのHTTPリクエストsupertest と組み合わせて Express アプリの統合テストを行うとき(supertest は内部で superagent を使用)

インストール

# npm
npm install superagent

# yarn
yarn add superagent

# pnpm
pnpm add superagent

TypeScript の型定義は本体に同梱されています。

superagent の基本的な使い方

import superagent from 'superagent';

// async/await パターン(最も推奨)
async function fetchUser(userId: string) {
  try {
    const res = await superagent
      .get(`https://api.example.com/users/${userId}`)
      .set('Authorization', 'Bearer my-token')
      .set('Accept', 'application/json');

    console.log(res.status); // 200
    console.log(res.body);   // パース済みの JSON オブジェクト
  } catch (err: any) {
    // 4xx/5xx はエラーとしてスローされる
    console.error(err.status, err.response?.body);
  }
}

// POST でJSONを送信
async function createUser(name: string, email: string) {
  const res = await superagent
    .post('https://api.example.com/users')
    .send({ name, email })          // Content-Type: application/json が自動設定
    .set('X-API-Key', 'my-api-key');

  return res.body;
}

よく使うAPI

1. .query() — クエリパラメータの設定

// GET /api/users?status=active&page=2&limit=20
const res = await superagent
  .get('https://api.example.com/api/users')
  .query({ status: 'active', page: 2, limit: 20 });

// 複数回呼び出すとマージされる
const res2 = await superagent
  .get('https://api.example.com/api/users')
  .query({ status: 'active' })
  .query({ page: 2 });

2. .send() — リクエストボディの送信

// JSON(デフォルト)
const res = await superagent
  .post('https://api.example.com/api/posts')
  .send({ title: '記事タイトル', content: '本文' });

// フォームデータ
const res2 = await superagent
  .post('https://api.example.com/api/login')
  .type('form')
  .send({ username: 'admin', password: 'secret' });

3. .attach() / .field() — ファイルアップロード(マルチパート)

// Node.js でのファイルアップロード
const res = await superagent
  .post('https://api.example.com/api/upload')
  .field('description', 'プロフィール画像')   // テキストフィールド
  .attach('avatar', '/path/to/photo.jpg');    // ファイル添付

4. .timeout() — タイムアウト設定

const res = await superagent
  .get('https://api.example.com/api/slow-endpoint')
  .timeout({
    response: 5000,  // サーバーからの応答開始まで 5秒
    deadline: 60000, // リクエスト全体の制限時間 60秒
  });

5. .retry() — 自動リトライ

// ネットワークエラーや 5xx エラー時に最大3回リトライ
const res = await superagent
  .get('https://api.example.com/api/unstable')
  .retry(3);

// カスタム条件でリトライ
const res2 = await superagent
  .get('https://api.example.com/api/unstable')
  .retry(3, (err, res) => {
    // true を返すとリトライする
    if (err && err.timeout) return true;
    if (res && res.status === 429) return true;
    return false;
  });

6. .use() — プラグインの適用

import superagent from 'superagent';
import prefix from 'superagent-prefix';

const res = await superagent
  .get('/api/users')
  .use(prefix('https://api.example.com'))  // URLプレフィックスを付与
  .query({ page: 1 });

7. .redirects() — リダイレクト制御

// リダイレクトを最大2回まで許可(デフォルトは5回)
const res = await superagent
  .get('https://api.example.com/old-endpoint')
  .redirects(2);

// リダイレクトを無効化
const res2 = await superagent
  .get('https://api.example.com/old-endpoint')
  .redirects(0);

類似パッケージとの比較

特徴superagentaxiosnode-fetchky
ブラウザ対応❌(別パッケージ)
Node.js 対応✅(v1+)
API スタイルメソッドチェーン設定オブジェクトWeb標準 Fetch 準拠メソッドチェーン
Promise 対応
リトライ機能✅ 組み込み❌(要プラグイン)✅ 組み込み
ファイルアップロード.attach()FormDataFormDataFormData
プラグイン機構.use()interceptorshooks
バンドルサイズ(gzip)約50KB約13KB約2KB約9KB
週間DL数非常に多い最多多い増加中

選定の目安: メソッドチェーンの書き心地を重視するなら superagent、設定オブジェクトベースが好みなら axios、Web標準に寄せたいなら fetch/ky が適しています。

注意点・Tips

4xx/5xx はエラーとしてスローされる

superagent は res.ok(ステータス 2xx)でない場合、Promise を reject します。これは fetch API と異なる挙動です。

try {
  const res = await superagent.get('https://api.example.com/api/not-found');
} catch (err: any) {
  // err.status === 404
  // err.response.body にレスポンスボディが入る
  console.log(err.status);
  console.log(err.response.body);
}

.end() と Promise は混ぜない

.end(callback) を呼ぶとコールバックスタイルになり、Promise は返りません。async/await を使う場合は .end() を呼ばないでください。

// ❌ NG: .end() と await の併用
const res = await superagent.get('/api').end((err, res) => {});

// ✅ OK: await のみ
const res = await superagent.get('/api');

レスポンスの型を明示する

TypeScript で型安全にするには、res.body をキャストまたはバリデーションします。

interface User {
  id: string;
  name: string;
  email: string;
}

const res = await superagent.get('https://api.example.com/api/users/1');
const user = res.body as User; // 型アサーション

TLS/SSL 証明書の検証を無効化する(開発環境のみ)

// ⚠️ 本番環境では絶対に使わないこと
import https from 'node:https';

const res = await superagent
  .get('https://localhost:3000/api')
  .disableTLSCerts(); // Node.js 環境のみ

プラグインを活用する

superagent のエコシステムには便利なプラグインが多数あります。superagent-* で npm を検索してみてください。代表的なものとして:

  • superagent-no-cache — キャッシュ防止ヘッダーを自動付与
  • superagent-throttle — リクエストのスロットリング
  • superagent-mock — テスト用のモックレスポンス

まとめ

superagent は、メソッドチェーンによる読みやすいAPIと、リトライ・タイムアウト・プラグイン機構などの実用的な機能を兼ね備えたHTTPクライアントです。ブラウザと Node.js で同じコードが動く点も大きな利点で、特に supertest と組み合わせたAPIテストの文脈では今なお広く使われています。新規プロジェクトでは axios や ky も検討しつつ、チェーンAPIの書き心地やプラグインエコシステムを重視する場合には有力な選択肢です。