Skip to content

HttpClientでfetchを有効化する方法(Angular 17 SSR)

問題概要

Angular 17にアップデート後、次の警告が表示される場合があります:

NG02801: Angularが`HttpClient`で`fetch` APIが未使用と検出。サーバーサイドレンダリング(SSR)ではパフォーマンスと互換性のため`fetch`の有効化が強く推奨されます

この警告はアプリケーション機能を停止させませんが、SSR環境での最適な動作を保証するために即時対応が推奨されます。主な発生要因は:

  • HttpClientinject()で使用している
  • provideHttpClient()設定でwithFetch()が未実装
  • Angular 16以前からアップデートした際の設定見直し不足

解決策

app.config.tsprovideHttpClient()withFetch()を追加します:

typescript
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http'; // 変更点

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withFetch()), // withFetch()を追加
    provideRouter(routes),
    provideClientHydration()
  ]
};

実装手順

  1. 設定ファイルを開く
    src/app/app.config.tsを編集

  2. インポートの追加

    typescript
    import { provideHttpClient, withFetch } from '@angular/common/http';
  3. providers配列を修正
    provideHttpClient()provideHttpClient(withFetch())で置換

  4. サーバー再起動

    bash
    ng serve # アプリケーション再起動

動作確認ポイント

  • 開発サーバーとアプリケーションを別端末で実行している場合、両方再起動が必要
  • SSR使用時はnpm run build && npm run serveで本番ビルドを検証

技術的背景

なぜwithFetch()が必要か?

要因影響
SSR互換性XMLHttpRequestはNode.jsで非サポート
パフォーマンスfetch()はストリーミング処理に最適化
バンドルサイズ代替実装の不要による軽量化

Angular 17ではHttpClientのデフォルトバックエンドがfetchに移行されましたが、アップデートプロセスでは明示的な有効化が必要です。

警告NG02801の性質

  • エラーではなく警告:アプリケーションは動作するがSSRで問題発生リスクあり
  • 将来的な変更:Angular将来バージョンでデフォルト化される可能性
  • 最適化の機会:SSR時のハイドレーションエラー減少に寄与

トラブルシューティング

警告が消えない場合の対処法

  1. 依存関係の更新確認
    bash
    ng update @angular/core @angular/cli
  2. 設定の重複をチェック
    typescript
    // NG例:重複提供
    providers: [
      provideHttpClient(withFetch()),
      provideHttpClient() // 重複設定は削除
    ]
  3. モジュール方式の設定不使用を確認
    typescript
    // app.module.tsでのHttpClientModule使用は廃止

注意事項

provideHttpClient()HttpClientModule併用は不可です。スタンドアロンコンポーネント移行後はモジュール削除が必要:

typescript
// app.module.tsからHttpClientModuleを削除
import { HttpClientModule } from '@angular/common/http'; // 削除対象