Next.js Static Export (output: export) で next/image がエラーになる原因と対処法
Next.js Cloudflare Frontend React
結論
next.config.js に images: { unoptimized: true } を追加してビルドエラーを回避します。
// Next.js公式仕様:next.config.mjs の静的エクスポート設定
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
images: {
unoptimized: true, // 静的ビルド時の標準無効化設定
},
};
export default nextConfig;
発生原因:Next.js公式仕様における画像最適化サーバーの不在
Next.js公式ドキュメント(nextjs.org/docs/app/building-your-application/deploying/static-exports)の規定通り、<Image /> コンポーネントのデフォルトローダーは、リクエスト時に Node.js サーバー上で画像を動的リサイズ・WebP/AVIFへ変換します。
output: 'export'(SSG静的出力)を指定した場合、Node.js サーバーが存在しないため、画像最適化機能が動作せず、ビルド実行時に以下のエラーを出して停止します。
Error: Image Optimization using Next.js' default loader is not compatible with `next export`.
Possible solutions:
- Use `next start` to run a server, which includes the Image Optimization API.
- Configure `images.unoptimized = true` in `next.config.js`.
2つの解決策アプローチ
| アプローチ | images.unoptimized: true | カスタムローダー (loader: 'custom') |
|---|---|---|
| 仕組み | 画像リサイズをスキップし、元ファイルをそのまま配信 | Cloudflare Image Resizing や Imgix 等の外部CDNへ委譲 |
| 設定場所 | next.config.js | next.config.js または <Image loader={...} /> |
| メリット | 追加コストゼロで即座にビルドが成功する | 画像圧縮・WebP化による高いCore Web Vitalsスコア維持 |
設定手順
- Cloudflare Pages や GitHub Pages へデプロイするために
next.config.mjsにoutput: 'export'を設定する images: { unoptimized: true }を追加してビルドを実行する- 外部CDNで画像変換を行いたい場合は
loader: 'custom'を指定し、専用のローダー関数を定義する
// カスタムローダー(Cloudflare Image Resizing用)の記述例
export default function cloudflareLoader({ src, width, quality }) {
return `https://example.com/cdn-cgi/image/width=${width},quality=${quality || 75}/${src}`;
}