next/image: hostname is not configured under images in next.config
The optimizer only fetches hosts listed in remotePatterns. Fix the protocol, pathname and wildcard fields, or switch to a loader or proxy route.

Introduction & Quick Summary
Next.js refuses to optimize a remote image whose host is not on an allow list. The error names the exact prop and host:
Error: Invalid src prop (https://cdn.example.com/hero.jpg) on `next/image`,
hostname "cdn.example.com" is not configured under images in your `next.config.js`The allow list is deliberate: the optimizer fetches the URL on the server, so an open list would let any page request arbitrary addresses, including internal ones. Four things produce this error:
- A remote URL with no matching entry.
images.remotePatterns(or the olderimages.domains) has no host for it. - A pattern that is too narrow. A
pathnameof/images/**does not match/hero.jpg, and aprotocolofhttpsdoes not match anhttpURL. - The config file is not the one being loaded.
next.config.jsnext to an existingnext.config.mjsornext.config.ts, or a config edited in a monorepo package that the app does not extend. - A URL built at runtime. A host assembled from an environment variable never matches a literal entry unless the pattern is a wildcard.
| Symptom | Cause | Fix |
|---|---|---|
| Host not configured, one known CDN | Missing remotePatterns entry | Add protocol, hostname, pathname |
| Works for one path, fails for another | pathname too narrow | Use /** or the real prefix |
| Fails only in preview deploys | Host changes per deployment | Wildcard hostname or a proxy route |
Fails only for http:// URLs | Pattern is https only | Add a second pattern with protocol: "http" |
| Config edit has no effect | Wrong config file or stale cache | Confirm the loaded file, restart |
Core Mechanics, Signatures & Reproducible Setup
next/image renders an <img> with a src that points at /_next/image?url=...&w=...&q=.... On request, the server fetches the source URL, resizes it with the image optimizer, and caches the result. Before fetching, it validates the source against images.remotePatterns (and the older images.domains). The validation happens at render time for the src prop and again at the optimizer endpoint, so an invalid entry fails in development with a component stack and in production with a 400 from /_next/image.
A minimal reproduction needs one remote image and no configuration:
// app/page.tsx
import Image from "next/image";
export default function Page() {
return (
<Image
src="https://cdn.example.com/hero.jpg"
alt="Hero"
width={1200}
height={630}
/>
);
}Error: Invalid src prop (https://cdn.example.com/hero.jpg) on `next/image`,
hostname "cdn.example.com" is not configured under images in your `next.config.js`The fix is a pattern entry, not a looser prop:
// next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "cdn.example.com",
pathname: "/**"
}
]
}
};
export default nextConfig;Restart the dev server after editing the config; the pattern list is read when the server starts.
Key Comparison Table
remotePatterns replaced domains because a host alone is too broad. The two are still both accepted, which is why old guides produce configurations that nearly work.
| Option | Matches | Granularity | Status |
|---|---|---|---|
images.domains | Any path on the host, any protocol allowed by the URL | Host only | Deprecated, still read |
images.remotePatterns | Protocol, hostname, port, pathname, search | Full URL shape | Current |
images.localPatterns | Local paths passed to the optimizer | Path prefix | Current |
images.unoptimized | Nothing, disables the optimizer | Global | Escape hatch |
loader | Nothing, replaces the optimizer | Custom | When a CDN does the resizing |
A pattern is a set of constraints, and every field must match. Missing fields mean "any" for protocol and port, but pathname defaults to allowing the whole host.
| Field | Example | Matches | Does not match |
|---|---|---|---|
protocol | "https" | https://cdn.example.com/a.png | http://cdn.example.com/a.png |
hostname | "cdn.example.com" | That exact host | img.cdn.example.com |
hostname | "**.example.com" | Any subdomain | example.com itself |
port | "" | Default port only | :8080 |
pathname | "/images/**" | /images/a/b.png | /hero.png |
pathname | "/**" | Any path | Nothing on that host |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Read the error before editing the config
The message prints the host that failed. If it shows a host you did not expect, the src is being built somewhere else, often in a CMS response or an environment variable, and the config is not the bug.
// log the resolved URL on the server, not the prop you meant to pass
console.log("image src", process.env.NEXT_PUBLIC_CDN + "/hero.jpg");# check what the component actually rendered in the HTML
curl -s https://example.com/ | grep -o 'src="[^"]*_next/image[^"]*"' | head -3The url= parameter of /_next/image is the source that must be allowed. A double-encoded URL there usually means the src already contained a query string.
Wildcards for preview and multi-tenant hosts
Preview deployments and per-tenant subdomains generate a host per environment, so a literal entry cannot cover them. remotePatterns supports * for one segment and ** for any number of segments inside a hostname.
images: {
remotePatterns: [
{ protocol: "https", hostname: "**.example.com", pathname: "/uploads/**" },
{ protocol: "https", hostname: "*-example.vercel.app", pathname: "/**" }
]
}// a proxy route keeps the allow list literal
// app/cdn/[...path]/route.ts
export async function GET(_: Request, { params }: { params: Promise<{ path: string[] }> }) {
const { path } = await params;
const upstream = await fetch(`https://${process.env.CDN_HOST}/${path.join("/")}`);
return new Response(upstream.body, { headers: { "content-type": upstream.headers.get("content-type") ?? "image/jpeg" } });
}Then point src at /cdn/hero.jpg and add localPatterns: [{ pathname: "/cdn/**" }]. The proxy is more code but keeps a strict list and hides the origin from the browser.
Local images need localPatterns, not domains
localPatterns governs which app paths may be passed to the optimizer. A common failure after adding a query string is a local path rejected by a prefix rule.
images: {
localPatterns: [
{ pathname: "/assets/**" },
{ pathname: "/api/media", search: "?v=2" }
]
}<Image src="/api/media?v=2&id=9" alt="" width={800} height={600} />The search field must match exactly, including order, so prefer a versioned path over a cache-busting query.
Static export, unoptimized and loader
output: "export" has no image server, so every next/image runs with unoptimized: true and the allow list is not consulted. A CDN loader replaces the optimizer entirely, which also removes the host check.
const nextConfig: NextConfig = {
output: "export",
images: { unoptimized: true }
};const nextConfig: NextConfig = {
images: {
loader: "custom",
loaderFile: "./lib/image-loader.ts"
}
};// lib/image-loader.ts
export default function loader({ src, width, quality }: { src: string; width: number; quality?: number }) {
return `https://images.example.com/cdn-cgi/image/width=${width},quality=${quality ?? 75},format=auto/${src}`;
}With a loader, remotePatterns is ignored, so the CDN's own allow list becomes the security boundary.
quality and Next 16's fixed list
Next 16 only accepts quality values listed in images.qualities, default [75]. A component passing quality={90} fails.
images: {
qualities: [50, 75, 90],
remotePatterns: [{ protocol: "https", hostname: "cdn.example.com" }]
}<Image src="https://cdn.example.com/hero.jpg" alt="" width={1200} height={630} quality={90} />Self-hosted production and sharp
The optimizer needs sharp. Vercel provides it, a container or bare server may not, and the failure looks like a 500 from /_next/image rather than a configuration error.
npm install sharp
docker build -t app . && docker run -p 3000:3000 app
curl -sI "http://localhost:3000/_next/image?url=https%3A%2F%2Fcdn.example.com%2Fhero.jpg&w=640&q=75" | head -5The response should be 200 with content-type: image/webp. A 400 means the URL is not allowed, a 500 means the optimizer failed, and the server log distinguishes the two.
Common Compilation/Runtime Mistakes & Version Gotchas
Adding the host to domains only. It still works in many versions, but it allows every path on that host and is deprecated; a new entry belongs in remotePatterns.
Editing the wrong config file. Next.js resolves next.config.ts, next.config.mjs, and next.config.js and errors if two exist. In a monorepo, the app's own config is the one that matters, not the root.
Forgetting the protocol. A pattern without protocol accepts both, but a src of http:// on an HTTPS site is mixed content and is blocked by the browser regardless of the allow list.
Trailing slashes in pathname. /images/ matches nothing that ends in /images. Use /images/** when a prefix is intended.
Assuming fill bypasses validation. fill changes layout only; the src is validated the same way.
Version notes. remotePatterns accepts search since 14.2. localPatterns arrived in 15. Next 16 enforces images.qualities and removed the built-in Squoosh encoder, so sharp is expected. The hostname is not configured message has been stable since 11, but the "see more info" URL changed with the docs restructure.
Build the entry from the URL itself: copy the src out of the error, split it with the URL parser, and compare the host, port, and path against the pattern. When several patterns are in play, keep them in a scratch file and check each with the regex tester before pasting back.
Official references: next/image component and Invalid images config.
Official references
primary documentationThe Next.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesModule not found: Can't resolve a package or alias in Next.js
TypeScript and the bundler resolve imports separately. Align path aliases, workspace dependencies, exports conditions and filename case.
next/font: Failed to fetch a Google font during the build
The font is fetched during the build, not at runtime. Vendor it with next/font/local or give CI and Docker a route out.
Tailwind CSS 4: the PostCSS plugin error and the v3 leftovers behind it
The moved PostCSS plugin is only half of it. Match the config extension, drop autoprefixer and postcss-import, and check for a second v3 copy.
Next.js cacheComponents: 'used uncached or runtime data' build error
Cache Components makes the build refuse to guess where the static shell ends. Stream it, cache it with use cache, or declare the route blocking.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.