できない.dev

Next.js の next/image で画像が表示できない

`next/image` は外部ドメイン画像に `images.remotePatterns` の許可が必須で、`width` / `height` の指定も要る。
ローカル画像は `/public` 配下に置き絶対パスで参照する。

#nextjs#image#remotePatterns#hostname#optimization

公開:

要約

next/image で画像が表示できないときは、外部ドメインの許可不足・サイズ未指定・パス間違い のいずれかがほぼ原因。
Invalid src prop」「hostname is not configured」「Image is missing required width property」が代表的なエラー表記。

よくある原因

  1. 外部ドメインを許可していない: 「hostname "images.example.com" is not configured under images」エラーが出る
  2. サイズ未指定: 「Image is missing required width / height property」エラー
  3. パス指定の間違い: /public/foo.pngsrc="./foo.png" のように相対指定している
  4. 静的エクスポート: output: 'export' は組み込みの画像最適化を使えない
  5. CORS / 認証: クロスオリジン制限や認証必須 URL で画像取得がブロックされている

解決策

1. 外部ドメインを許可する

公式の images 設定ドキュメント に従い next.config.js を編集する。

module.exports = {
  images: {
    remotePatterns: [
      { protocol: "https", hostname: "images.example.com" },
    ],
  },
};

設定変更後は dev server を必ず再起動する。

2. サイズを必ず指定する

import Image from "next/image";
 
export function Hero() {
  return <Image src="/hero.png" alt="hero" width={1200} height={630} />;
}

サイズが不明な場合は親要素を position: relative にして fill を使う。

<div style={{ position: "relative", width: 320, height: 240 }}>
  <Image src="/hero.png" alt="hero" fill />
</div>

3. 静的エクスポート時の対応

output: 'export' を使うプロジェクトでは、組み込みの画像最適化サーバーが動かない。images.unoptimized: true を設定するか、Cloudinary などの外部ローダーを設定する。
Image コンポーネントの仕様詳細は公式の <Image> リファレンス を参照する。

この記事は役立ちましたか?