Next.jsで、Imageコンポーネントエラーを解消する方法

TwitterFacebookHatena
  • 公開:2023-10-25
  • 更新:2023-10-26
  • 文章量:2407
  • Next.js

TL;DR

この記事では、Next.js の img タグや、<Image />コンポーネントを使ったときのエラーとその解決策について解説します。

開発環境 バージョン
Next.js 13.4.3
TypeScript 5.0.4
React 18.2.0

ESLint の警告

Next.js で、img タグを使うと以下のような警告が出ることがあります。

Using <img> could result in slower LCP and higher bandwidth. Consider using <Image /> from next/image to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element",

このメッセージは、Next.js の ESLint プラグインから出力される警告で「通常の HTML の<img>タグを使用すると、LCP(Largest Contentful Paint、最も大きなコンテンツの描画時間)が遅くなる可能性があり、さらに帯域幅も多く使う可能性がある」ということを伝えています。

例えば、以下のような<Image />を使った記述で画像を表示することが望ましいです。

import Image from "next/image";

function Home() {
  return (
    <Image
      src="https://example.com/sample.jpg"
      alt="sample image"
      width={600}
      height={400}
    />
  );
}

export default Home;

No img element | Next.js

画像を最適化するために、Next.js が提供する<Image />コンポーネントを使うことを検討してください。このコンポーネントは、next/imageからインポートできます。このコンポーネントは、画像の最適化を自動で行ってくれます。

TypeScript では、次のような記述になるでしょう。

import Image from "next/image";

type Props = {
  src: string;
  alt: string;
  width: number;
  height: number;
};

const OptimizedImage = ({ src, alt, width, height }: Props) => {
  return (
    <div>
      <Image
        src={src}
        alt={alt}
        width={width}
        height={height}
        layout="responsive"
      />
    </div>
  );
};

OAuth 認証時の外部 URL のエラー

例えば、Google の OAuth 認証を実装する場合、次のようなエラーが発生することがあります。

Unhandled Runtime Error Error: Invalid src prop (https://lh3.googleusercontent.com/xxxx) on next/image, hostname "lh3.googleusercontent.com" is not configured under images in your next.config.js See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host

このエラーは、Next.js の<Image />コンポーネントが外部の URL を読み込む際に必要な設定がnext.config.jsにないために発生しています。外部の画像(この場合は Google の画像)を使用する場合、そのドメインをnext.config.jsに設定する必要があります。

next.config.jsをプロジェクトのルートディレクトリに作成(または既存のものを編集)し、以下のように設定してください。

module.exports = {
  images: {
    domains: ["lh3.googleusercontent.com"],
  },
};

この設定を追加した後、開発サーバーを再起動してください。

これで、lh3.googleusercontent.comからの画像を<Image />コンポーネントで読み込むことができるようになります。詳細はNext.js のドキュメントを参照してください。

複数の外部 URL を使用する場合、next.config.js ファイルに以下のような設定を追加する必要があります。

module.exports = {
  images: {
    domains: ["example.com", "another-example.com"],
  },
};

domains 配列には、許可する外部ドメインを追加します。

Next.jsで、Imageコンポーネントエラーを解消する方法