Error: Invalid src prop on `next/image`, hostname is not configured
What causes this
Next.js optimizes images through its built-in Image component, but for security reasons it only allows images from explicitly whitelisted hostnames. When you use an external URL as the src prop, Next.js blocks it unless you’ve added that domain to your config.
This is a deliberate security measure — without it, attackers could abuse your image optimization endpoint to proxy and resize arbitrary images, consuming your server resources.
Fix 1: Add the hostname to next.config.js (Next.js 14+)
The modern approach uses remotePatterns:
// next.config.js
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.example.com',
},
{
protocol: 'https',
hostname: '**.amazonaws.com',
},
],
},
};
module.exports = nextConfig;
Wildcards work with ** for subdomains. Restart your dev server after changing the config.
Fix 2: Use the older domains config
For simpler cases or older Next.js versions:
// next.config.js
const nextConfig = {
images: {
domains: ['cdn.example.com', 'images.unsplash.com'],
},
};
module.exports = nextConfig;
Note: domains is deprecated in favor of remotePatterns but still works.
Fix 3: Allow specific paths only
Lock it down further by restricting to specific paths:
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.example.com',
pathname: '/uploads/**',
},
],
This only allows images from https://cdn.example.com/uploads/....
Fix 4: Use unoptimized for one-off images
If you don’t need optimization for a specific image:
import Image from 'next/image';
<Image
src="https://external-site.com/photo.jpg"
alt="Photo"
width={800}
height={600}
unoptimized
/>
Or disable optimization globally (not recommended for production):
// next.config.js
const nextConfig = {
images: { unoptimized: true },
};
Fix 5: Handle dynamic hostnames from a CMS
When images come from user-generated content or a CMS with unpredictable domains:
remotePatterns: [
{
protocol: 'https',
hostname: '**', // allows any hostname — use with caution
},
],
⚠️ Only do this if you trust all image sources. A better approach is to proxy images through your own CDN.
Related resources
How to prevent it
- Add all known image domains to
remotePatternsupfront when setting up a project - Use
remotePatternsoverdomains— it’s more flexible and the recommended approach - Always restart the dev server after changing
next.config.js - For user-uploaded images, route them through your own storage (S3, Cloudinary) so you only need one hostname