iTranslated by AI
Next.js 14 Deprecates 'domains' for External Image Loading in <Image>
Situation
I was implementing a feature to allow logins with GitHub and Google accounts using NextAuth.js (App Router environment). While the login itself started to work, a warning occurred during next build because I was using <img> tags to display the logged-in user's image. A message was displayed suggesting that images should be optimized using <Image> from next/image.
Warning: 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
External Domain Image Loading Restrictions with <Image>
Even after changing from <img> to <Image> (and setting the alt attribute, etc.), the images are not displayed when checking them.
To protect the application from user attacks, <Image> has a built-in mechanism that restricts loading images from external domains. To load images, it is necessary to specify the domains that allow image loading in next.config.js.
module.exports = {
images: {
// Allow loading of Google and GitHub account images
domains: [
'lh3.googleusercontent.com',
'avatars.githubusercontent.com'
],
},
}
By adding the above settings, the images started to load and the issue was successfully resolved 🙌
...or so it seemed, but another warning occurred during next build again.
⚠ The "images.domains" configuration is deprecated. Please use "images.remotePatterns" configuration instead.
It appears that from Next.js 14, the use of domains has been deprecated except in some situations, and the use of remotePatterns is now recommended instead.
Warning: Deprecated since Next.js 14 in favor of strict remotePatterns in order to protect your application from malicious users. Only use domains if you own all the content served from the domain.
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'lh3.googleusercontent.com'
},
{
protocol: 'https',
hostname: 'avatars.githubusercontent.com'
}
]
}
With the configuration using remotePatterns, loading external domain images can now be done without warnings 🥳
remotePatterns
In remotePatterns, it seems you can restrict image loading by returning a 400 Bad Request when a request is made for an unspecified protocol, hostname, port, or a path that does not match the pattern.
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
}
Discussion