Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readNext.js
#Next.js#Images#Configuration#Performance
A remote image crate blocked at a cyan allow list gate, an amber host pattern plate and wildcard key

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:

text
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 older images.domains) has no host for it.
  • A pattern that is too narrow. A pathname of /images/** does not match /hero.jpg, and a protocol of https does not match an http URL.
  • The config file is not the one being loaded. next.config.js next to an existing next.config.mjs or next.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.
SymptomCauseFix
Host not configured, one known CDNMissing remotePatterns entryAdd protocol, hostname, pathname
Works for one path, fails for anotherpathname too narrowUse /** or the real prefix
Fails only in preview deploysHost changes per deploymentWildcard hostname or a proxy route
Fails only for http:// URLsPattern is https onlyAdd a second pattern with protocol: "http"
Config edit has no effectWrong config file or stale cacheConfirm 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:

jsx
// 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} /> ); }
text
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:

ts
// 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.

OptionMatchesGranularityStatus
images.domainsAny path on the host, any protocol allowed by the URLHost onlyDeprecated, still read
images.remotePatternsProtocol, hostname, port, pathname, searchFull URL shapeCurrent
images.localPatternsLocal paths passed to the optimizerPath prefixCurrent
images.unoptimizedNothing, disables the optimizerGlobalEscape hatch
loaderNothing, replaces the optimizerCustomWhen 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.

FieldExampleMatchesDoes not match
protocol"https"https://cdn.example.com/a.pnghttp://cdn.example.com/a.png
hostname"cdn.example.com"That exact hostimg.cdn.example.com
hostname"**.example.com"Any subdomainexample.com itself
port""Default port only:8080
pathname"/images/**"/images/a/b.png/hero.png
pathname"/**"Any pathNothing 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.

ts
// 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 -3

The 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.

ts
images: { remotePatterns: [ { protocol: "https", hostname: "**.example.com", pathname: "/uploads/**" }, { protocol: "https", hostname: "*-example.vercel.app", pathname: "/**" } ] }
ts
// 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.

ts
images: { localPatterns: [ { pathname: "/assets/**" }, { pathname: "/api/media", search: "?v=2" } ] }
jsx
<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.

ts
const nextConfig: NextConfig = { output: "export", images: { unoptimized: true } };
ts
const nextConfig: NextConfig = { images: { loader: "custom", loaderFile: "./lib/image-loader.ts" } };
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.

ts
images: { qualities: [50, 75, 90], remotePatterns: [{ protocol: "https", hostname: "cdn.example.com" }] }
jsx
<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 -5

The 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 documentation

The Next.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.