Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Image and Font Optimization: priority, sizes, and remotePatterns

Why an image without sizes downloads 1600 pixels on a phone, what priority is for, the positioned parent that fill requires, and how next/font removes font shift.

~4 min readNext.js
#Next.js#Performance#Images#Fonts
3D illustration of a picture frame splitting into resolution variants and a font card with a swap arrow

Quick Summary

next/image and next/font each solve one problem at build time rather than in the browser. The image component generates responsive srcset variants, serves modern formats, and reserves layout space so nothing jumps; the font loader self-hosts the font files, inlines a size-adjusted fallback, and eliminates the layout shift a web font normally causes.

Both need accurate configuration to help. width and height (or fill with a positioned parent) are required, because they are how the layout box is reserved — omitting them is the single most common cause of layout shift. sizes tells the browser which candidate to download; a wrong sizes downloads a 4K image on a phone. priority marks the one image that is the Largest Contentful Paint and preloads it; setting priority on everything removes the benefit and competes with the font preloads.

Remote images must be declared in next.config with images.remotePatterns — a hostname allow-list that replaced the older, looser domains. Google Fonts are fetched at build time by next/font/google, which means the build needs network access and a font that is not available fails the build rather than the page.

Basic Syntax & Core Signatures

tsx
import Image from "next/image"; // Fixed-size image <Image src="/hero.png" alt="Deployment pipeline" width={1200} height={630} priority /> // Responsive image filling a sized parent <div style={{ position: "relative", aspectRatio: "16 / 9" }}> <Image src="/hero.png" alt="Deployment pipeline" fill sizes="(max-width: 768px) 100vw, (max-width: 1280px) 50vw, 640px" style={{ objectFit: "cover" }} /> </div> // Remote image with an explicit size and a blur placeholder <Image src="https://cdn.example.com/products/a.jpg" alt="Product" width={640} height={480} sizes="(max-width: 640px) 100vw, 320px" placeholder="blur" blurDataURL="data:image/svg+xml;base64,..." />
ts
// next.config.ts const config = { images: { remotePatterns: [ { protocol: "https", hostname: "cdn.example.com", pathname: "/products/**" }, { protocol: "https", hostname: "*.googleusercontent.com" }, ], formats: ["image/avif", "image/webp"], deviceSizes: [360, 640, 768, 1024, 1280, 1536, 1920], minimumCacheTTL: 60 * 60 * 24 * 30, }, }; export default config;
tsx
// app/layout.tsx — a variable font for the whole app import { Inter, JetBrains_Mono } from "next/font/google"; const inter = Inter({ subsets: ["latin"], display: "swap", variable: "--font-sans" }); const mono = JetBrains_Mono({ subsets: ["latin"], display: "swap", variable: "--font-mono" }); export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en" className={`${inter.variable} ${mono.variable}`}> <body>{children}</body> </html> ); }
css
/* globals.css */ :root { --font-sans-stack: var(--font-sans), ui-sans-serif, system-ui, sans-serif; } body { font-family: var(--font-sans-stack); }
tsx
// Local font files: no network at build, full control import localFont from "next/font/local"; const brand = localFont({ src: [{ path: "./brand-regular.woff2", weight: "400" }, { path: "./brand-bold.woff2", weight: "700" }], display: "swap", variable: "--font-brand", });

Key Comparison Table

Prop / optionPurposeMistake
width + heightReserve layout space, set aspect ratioOmitting them → layout shift
fillFill a positioned parentParent without position: relative
sizesTells the browser the rendered widthMissing → downloads the largest
priorityPreload; for the LCP image onlyOn every image
placeholder="blur"Blur-up while loadingNeeds blurDataURL for remote images
qualityOutput quality (default 75)Raising it to 100 for text-heavy photos
unoptimizedSkip the optimizerUsed for SVGs it cannot improve
remotePatternsAllow-list for remote hostsOld domains syntax, too broad
Font optionEffectDefault
subsetsWhich glyph ranges to downloadRequired for Google fonts
displayfont-display behaviourswap when specified
variableExpose a CSS custom propertynone
preloadPreload the font filetrue
adjustFontFallbackSize-adjusted fallback to kill CLStrue
SymptomMeaning
Invalid src prop ... hostname not configuredMissing remotePatterns entry
Images render at 0 heightfill without a positioned parent
Largest image fetched on mobilesizes missing or wrong
Layout jumps on loadNo intrinsic size and no aspect ratio
Font flashes or shiftsdisplay or fallback adjustment

Practical Edge Cases & Deep Dives

1. sizes is the difference between 40 KB and 400 KB

tsx
// Rendered at half the viewport on desktop, full width on mobile <Image src={src} alt="" width={1600} height={900} sizes="(max-width: 768px) 100vw, 50vw" />

The browser picks a candidate from the generated srcset using sizes. Omit sizes and it assumes the image fills the viewport, so a 320 px phone downloads the 1600 px variant. A grid of three cards should say sizes="(max-width: 768px) 100vw, 33vw". When the layout is dynamic, line the values up with the CSS breakpoints — a mismatch silently costs bandwidth on the widest screens.

2. priority and the Largest Contentful Paint

tsx
<Image src="/hero.jpg" alt="Hero" width={1920} height={1080} priority />

priority adds a <link rel="preload"> and stops lazy-loading for that image. It should be on exactly one image per page — usually the hero — because preloads compete with each other and with font preloads for the same connection. Every other image is lazy by default, which is correct: below-the-fold images should not be fetched before they are needed.

3. fill and the parent that is not positioned

tsx
<div> {/* no position: relative */} <Image src={src} alt="" fill /> </div>

fill positions the image absolutely against the nearest positioned ancestor. Without one, it escapes to the page and either covers the layout or collapses to zero height. The reliable pattern is a wrapper with position: relative and an explicit aspectRatio, which also fixes layout shift without needing width/height.

4. Remote patterns: narrow by host and path

ts
images: { remotePatterns: [ { protocol: "https", hostname: "images.ctfassets.net", pathname: "/abc123/**" }, ], }

The image optimizer fetches whatever URL you give it, so remotePatterns is an SSRF guard as much as a configuration. A wildcard hostname (**.example.com) or a missing pathname lets a crafted src fetch arbitrary paths from that host through your server. Keep pathname as specific as the CDN layout allows.

5. Fonts: display, fallbacks, and what next/font actually writes

tsx
const inter = Inter({ subsets: ["latin"], display: "swap" });

next/font downloads the font at build time, emits self-hosted woff2 files under /_next/static/media, generates @font-face rules with font-display: swap, and produces a fallback face whose metrics are adjusted (size-adjust, ascent-override) to match — which is what removes the shift when the real font arrives. display: "optional" is the alternative for a font that must never cause a shift (the browser may not use it at all on a slow connection).

A Google font that is not in subsets silently drops glyphs: a Korean page loading subsets: ["latin"] renders tofu for Hangul. Use ["latin", "latin-ext"] plus the relevant script subset, or a local font when the subset is not offered.

Common Runtime & Configuration Mistakes

SymptomCauseFix
hostname not configured under imagesMissing remotePatternsAdd protocol, host, path
Image collapses to zero heightfill with no positioned parentposition: relative + aspectRatio
Huge downloads on mobileNo sizesSet breakpoint-accurate sizes
Everything preloads, nothing is fastpriority on many imagesOnly the LCP image
Layout shift on font loaddisplay missing or fallback not adjusteddisplay: "swap", adjustFontFallback
Fonts work in dev, 404 in productionLocal font path outside the bundleKeep the file beside the component
Build fails offlineGoogle font fetched at buildVendor the font with localFont
Blur placeholder never showsRemote image without blurDataURLProvide a tiny data URL
Images re-optimized on every deployCDN cache cleared with the deployRaise minimumCacheTTL
SVG looks wrongRaster optimizer appliedunoptimized for SVG

Images and fonts are the two biggest causes of both layout shift and bandwidth waste, and next/image plus next/font fix them only when the sizes, the priority flag, the remote allow-list, and the font subset are all accurate. Set them from the real layout, not from the largest possible case.

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.