Next.js next/image で外部URLの画像を使いたいときにやること
プロトタイプを作っているときなど、ダミー画像で画像生成サービスを使うことがあります。
Next.js の組み込みコンポーネント next/image でダミー画像生成サービスの url を src に設定したらエラーになったので忘れないようにメモ。
next/image の src に外部ドメインを指定するとエラーになる
import { VFC } from "react"; import Image from 'next/image'; type AvatarProps = { alt?: string; width: number; height: number; } const dummyImage = 'https://placeimg.com/140/140/any'; export const Avatar: VFC = ({ alt, width, height }) => { return ( <Image src={dummyImage} width={width} height={height} alt={alt} /> ); };
=> Server Error
Error: Invalid src prop (https://placeimg.com/140/140/any) on `next/image`, hostname "placeimg.com" is not configured under images in your `next.config.js`
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host
エラーになります。
next.config.js に使用する外部ドメインを設定しておく必要がある
To enable Image Optimization for images hosted on an external website, use an absolute url for the Image
srcand specify whichdomainsare allowed to be optimized. This is needed to ensure that external urls can't be abused. Whenloaderis set to an external image service, this option is ignored.
cf. Basic Features: Image Optimization | Next.js
next/image が画像最適化を行うために外部ドメインの画像を使う場合はドメインを指定しておく必要がある。トノコト
next.config.js が無ければ作る。
$ touch next.config.js
👇
next.config.js
module.exports = { images: { domains: ['placeimg.com'], }, };
今回は https://placeimg.com/140/140/any を使いたいので domains には placeimg.com を指定する
設定ファイルなので反映させるにはサーバーを再起動させる必要がある。
ctl + C でサーバーを止めて npm run dev で再起動。
Avatar コンポーネントの画像が問題なく表示されていれば OK
[参考]
今季は かげきしょうじょ 観てます。オススメあったら教えてください!

