0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js】next/imageの画像がローカルで読み込めていたのに本番環境では404となり読み込めなくなった

Last updated at Posted at 2025-04-01

概要

Next.js で開発中に画像が正常に表示されるのに、本番環境にデプロイすると画像が表示されない問題に直面。
next export を使用して静的サイトとしてデプロイする場合、デフォルトの next/image の最適化機能が影響を与える可能性があるらしいとのことで、試してみたら解決したので記事にします

画像が表示されない問題

現象

Next.js で開発環境 (npm run dev) では、以下のようなコードで画像を表示できる。

import Image from "next/image";

export default function MyComponent() {
  return (
    <div>
      <Image src="/images/main_image.jpg" alt="Main Image" width={1080} height={720} />
    </div>
  );
}

このコードは、ローカル環境では正常に画像を表示できるが、本番環境にデプロイすると、/_next/image?url=... という URL で画像を取得しようとするものの、404 エラーが発生し、画像が表示されない問題が発生した。

確認したこと

  1. public/ 内に images/main_image.jpg があるか確認 → 存在する
  2. /_next/static/media/ に画像が配置されているか確認 → ない
  3. next.config.js の設定を見直し → デフォルト設定のまま
  4. next/image の最適化が影響している可能性を調査

この結果、next export を使用したビルドでは next/image の最適化機能がデフォルトで有効になっており、それが原因で画像が正しく表示されていないことが判明した。

解決方法

原因

Next.js では、next/image はデフォルトで Vercel の画像最適化機能を使用するようになっているいっぽうで、next export を使用して静的サイトをデプロイすると、この最適化機能は使用できなくなるっぽい。

対策

この問題を解決するためには、next.config.jsunoptimized: true を設定し、Next.js の画像最適化を無効化するとよさそうだとわかった。

1. next.config.js を編集

next.config.js に以下の設定を追加。

module.exports = {
  images: {
    unoptimized: true, // 画像の最適化を無効化
  },
};

2. ビルドとデプロイ

この設定を追加したら、次のコマンドでビルドをやり直す。

npm run build
npm run export

これをデプロイすると、正しく表示できました!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?