HttpClientでfetchを有効化する方法(Angular 17 SSR)
問題概要
Angular 17にアップデート後、次の警告が表示される場合があります:
NG02801: Angularが`HttpClient`で`fetch` APIが未使用と検出。サーバーサイドレンダリング(SSR)ではパフォーマンスと互換性のため`fetch`の有効化が強く推奨されます
この警告はアプリケーション機能を停止させませんが、SSR環境での最適な動作を保証するために即時対応が推奨されます。主な発生要因は:
HttpClient
をinject()
で使用しているprovideHttpClient()
設定でwithFetch()
が未実装- Angular 16以前からアップデートした際の設定見直し不足
解決策
app.config.ts
でprovideHttpClient()
に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()
]
};
実装手順
設定ファイルを開く
src/app/app.config.ts
を編集インポートの追加
typescriptimport { provideHttpClient, withFetch } from '@angular/common/http';
providers配列を修正
provideHttpClient()
をprovideHttpClient(withFetch())
で置換サーバー再起動
bashng serve # アプリケーション再起動
動作確認ポイント
- 開発サーバーとアプリケーションを別端末で実行している場合、両方再起動が必要
- SSR使用時は
npm run build && npm run serve
で本番ビルドを検証
技術的背景
なぜwithFetch()
が必要か?
要因 | 影響 |
---|---|
SSR互換性 | XMLHttpRequest はNode.jsで非サポート |
パフォーマンス | fetch() はストリーミング処理に最適化 |
バンドルサイズ | 代替実装の不要による軽量化 |
Angular 17ではHttpClient
のデフォルトバックエンドがfetch
に移行されましたが、アップデートプロセスでは明示的な有効化が必要です。
警告NG02801の性質
- エラーではなく警告:アプリケーションは動作するがSSRで問題発生リスクあり
- 将来的な変更:Angular将来バージョンでデフォルト化される可能性
- 最適化の機会:SSR時のハイドレーションエラー減少に寄与
トラブルシューティング
警告が消えない場合の対処法:
- 依存関係の更新確認bash
ng update @angular/core @angular/cli
- 設定の重複をチェックtypescript
// NG例:重複提供 providers: [ provideHttpClient(withFetch()), provideHttpClient() // 重複設定は削除 ]
- モジュール方式の設定不使用を確認typescript
// app.module.tsでのHttpClientModule使用は廃止
注意事項
provideHttpClient()
とHttpClientModule
の併用は不可です。スタンドアロンコンポーネント移行後はモジュール削除が必要:
typescript
// app.module.tsからHttpClientModuleを削除
import { HttpClientModule } from '@angular/common/http'; // 削除対象