はじめに
Next.js 15でunsplash
の画像を引用した際に以下のエラーが発生した。
Error: Invalid src prop (https://images.unsplash.com/photo-1544947950-fa07a98d237f?auto=format&fit=crop&q=80&w=200) on `next/image`, hostname "images.unsplash.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ではセキュリティ上の理由から、
外部画像を読み込む際に使用するホスト名を明示的に許可する必要がある。
対処方
next/image
コンポーネントを使用する際、外部ホスト名をnext.config.js
に定義する。
-
next.config.js
を編集
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'images.unsplash.com',
port: '',
pathname: '/**',
},
],
},
};
export default nextConfig;
以上です