Next.jsのImageコンポーネントを使ってmicroCMSのアイキャッチ画像を表示しようとしたら
Server Error Error: Invalid src prop (https://images.microcms-assets.io/assets/3c070efふんがふんが・・・
と、いつもの画面がでてきて、いつものように何言ってるかわからなかったけど、解決できたので備忘録として残します。
結論:
next.config.jsっていう名前のファイルをルートディレクトリに作成し以下のコードをコピペ、
すでにある場合はimages:{}の部分を追記
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'images.microcms-assets.io
',
port: '',
pathname: '/**',
},
],
},
}
すでにある場合
//Next v13.1.1だとすでにあったので
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
//ここから
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'images.microcms-assets.io',
port: '',
pathname: '/**',
},
],
},
//ここまでが追記
}
module.exports = nextConfig
ちなみに出たエラーはこちら

とりあえず日本語でおkなので翻訳してみると
Server Error Error: Invalid src prop (https://images.microcms-assets.io/assets/3c07fungafunga0ef7/love.jpg) onnext/image
, hostname "images.microcms-assets.io" is not configured under images in yournext.config.js
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host 翻訳 サーバーエラー エラー 無効な src prop (https://images.microcms-assets.io/assets/3c07ふんがふんが0ef7/love.jpg) onnext/image
, next.config.jsのimagesの下にホスト名 "images.microcms-assets.io "が設定されていない。 詳細はこちら: https://nextjs.org/docs/messages/next-image-unconfigured-host
next.config.jsのimagesの下にホスト名 "images.microcms-assets.io "が設定されていない。
よくわからない人はnext.config.jsのリファレンス見てこいや、とのことが書いてあるので
仰せのままにリンクをクリック。
エラー下の方のSee more info: のとこ
https://nextjs.org/docs/messages/next-image-unconfigured-host
そもそもNext.jsでは外部URLから画像を表示する場合
next.config.jsとやらにremotePatternsっていうのを追記して外部URLを書いてやらないとだめらしい
microCMSの画像はどこからやってくるのか
microCMSのAPIプレビューの取得で取得できるAPIをみてみる。

“https://images.microcms-assets.io/assets/“
ってとこから画像をもってきてるっぽいので
remotePatternsの中の
hostname:に'images.microcms-assets.io'
pathname:に'/**'
と書いた。
このremotePatternsにいれる書き方はNext.js v12.3.0から安定して使えるようになったらしく
それより前のバージョンで使う場合はremotePatternsではなくdmains:[‘ゆあどめいん’]に書くみたい。
とりあえずnext.config.jsを書き換えてcontrl+cでサーバーを一度終了。
npm ランデブーしてみると。

無事画面いっぱいに愛キャッチ画像が表示されました。