错误:`next/image` 上的 src prop 无效,主机名 "example.com" 未在 images.remotePatterns 中配置
Error: Invalid src prop on `next/image`, hostname "example.com" is not configured under images.remotePatterns
ID: nextjs/next-image-unconfigured-hostname
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Next.js 13.0.0 | active | — | — | — |
| Next.js 14.0.0 | active | — | — | — |
| Next.js 14.2.0 | active | — | — | — |
根因分析
Next.js 的 Image 组件要求在 next.config.js 的 images.remotePatterns 中明确允许外部图片主机名,以确保安全和优化;否则会抛出此错误。
English
Next.js Image component requires external image hostnames to be explicitly allowed in next.config.js under images.remotePatterns for security and optimization; otherwise, it throws this error.
官方文档
https://nextjs.org/docs/app/api-reference/components/image#remotepatterns解决方案
-
Add the hostname to next.config.js: 'images: { remotePatterns: [{ protocol: "https", hostname: "example.com" }] }' -
If using Next.js 14+, use the 'images.unoptimized: true' config to disable all image optimization (not recommended for production).
-
For multiple hostnames, add each one: 'images: { remotePatterns: [{ protocol: "https", hostname: "example.com" }, { protocol: "https", hostname: "cdn.example.com" }] }'
无效尝试
常见但无效的做法:
-
70% 失败
images.domains is deprecated since Next.js 13; images.remotePatterns is the required configuration.
-
60% 失败
remotePatterns requires explicit protocol and hostname; wildcards must be in the hostname field, not as a string pattern.
-
80% 失败
This bypasses optimization but still requires the hostname to be configured for security; the error persists.