In Next.js, loading images from external domains requires configuration in next.config.js
. You can allow images from all domains either by using remotePatterns
with a wildcard or by disabling image optimization entirely with unoptimized
.
๐ If youโre dealing with an external image provider, you might run into these cases, so pick the right one based on your needs. ๐
Method 1: Using remotePatterns
(Updated) โ
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "*", // Allow images from all domains
},
],
},
};
export default nextConfig;
Method 2: Using unoptimized
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
unoptimized: true, // Disable image optimization
},
};
export default nextConfig;
When to Use:
-
remotePatterns
: When you want optimized images and flexibility. -
unoptimized
: When you need images from any domain without optimization.
This approach helps in handling dynamic image sources and bypassing domain restrictions. ๐ฅ
โ Update: Big thanks to Ajit Kumar for pointing out an important detail in the comments. He mentioned that using "*" as a wildcard for hostname in remotePatterns is not allowed due to security reasons. Iโve updated the post to reflect the correct configuration to stay up-to-date with Next.js best practices. ๐
Top comments (3)
Does it remotepatterns still valid in new version of Nextjs? I was seeing some options like domains have depreciated in latest release.
I think, remotepatterns is replacement of domains in nextjs 15. Thanks. I will explore it further.
I think, wildcard "" is not allowed due to security risk.
Error: Invalid images.remotePatterns configuration:
Pattern hostname "" is not allowed.
Hey Ajit Kumar! ๐
Thanks for pointing that out! You were totally right about the "*" wildcard. Iโve updated the post now. Appreciate it! ๐