Optimizing Images in Next.js Static Export
next/image is one of Next.js's best features on a server: it resizes, re-encodes and caches images on demand, generating exactly the width and format each browser needs. Turn on output: 'export' for a static site and it stops working. The default loader depends on the Next.js server's /_next/image endpoint, which does not exist in a folder of static files, and the build fails with an error suggesting images.unoptimized: true. Many teams accept that suggestion and ship original images at every size.
This guide compares three ways to get responsive, modern-format images back in a static export — build-time generation, a custom loader for an image CDN, and doing nothing — on a 600-post Next.js blog, measuring bytes and LCP. It is part of Next.js Static Export for Content Sites.
Prerequisites
- A Next.js 14 or 15 site with
output: 'export'innext.config.js. - Images stored in the repository or in an object store you control.
- Lighthouse or WebPageTest to measure LCP and image bytes before and after.
Option 0: unoptimized: true (the Baseline)
// next.config.js
module.exports = { output: 'export', images: { unoptimized: true } };
<Image> still renders width, height and lazy loading, which prevents layout shift and defers offscreen images. But srcset contains only the original, so a phone downloads the same 2400-pixel JPEG as a 4K monitor. On the blog, the median post hero was 780 KB.
Option 1: Generate Variants at Build Time
Generate a fixed set of widths and formats for every image during the build, and point <Image> at them with a loader that picks the right file. The next-export-optimize-images package automates this; the underlying approach is a sharp script run after next build:
// scripts/optimize-images.mjs — runs after `next build`
import sharp from 'sharp';
import { globSync, mkdirSync } from 'node:fs';
const WIDTHS = [640, 960, 1280, 1920];
for (const src of globSync('public/images/**/*.{jpg,jpeg,png}')) {
const name = src.replace(/^public\/images\//, '').replace(/\.\w+$/, '');
for (const w of WIDTHS) for (const fmt of ['avif', 'webp']) {
const out = `out/_img/${name}-${w}.${fmt}`;
mkdirSync(out.replace(/\/[^/]+$/, ''), { recursive: true });
await sharp(src).resize({ width: w, withoutEnlargement: true })
[fmt]({ quality: fmt === 'avif' ? 50 : 72 }).toFile(out);
}
}
// image-loader.js — referenced from next.config.js images.loaderFile
const WIDTHS = [640, 960, 1280, 1920];
export default function loader({ src, width }) {
const w = WIDTHS.find((x) => x >= width) ?? WIDTHS.at(-1);
return `/_img/${src.replace(/^\/images\//, '').replace(/\.\w+$/, '')}-${w}.webp`;
}
// next.config.js
module.exports = { output: 'export', images: { loader: 'custom', loaderFile: './image-loader.js', deviceSizes: [640, 960, 1280, 1920] } };
The loader emits WebP; for AVIF with WebP fallback, render a <picture> in a small wrapper component around <Image>, as covered in Serving AVIF with Fallbacks on Static Sites. Cache out/_img between CI runs keyed by a hash of the source images, or the step reprocesses everything on every build.
Option 2: A Custom Loader for an Image CDN
If images already live on, or can be served through, an image CDN — Cloudflare Images or Image Resizing, imgix, Cloudinary, or a self-hosted imgproxy — a loader that builds CDN URLs is the smallest change:
// image-loader.js (Cloudflare Image Resizing)
export default function loader({ src, width, quality }) {
return `https://images.example.com/cdn-cgi/image/width=${width},quality=${quality ?? 75},format=auto${src}`;
}
format=auto serves AVIF or WebP by the browser's Accept header, and every width in deviceSizes is available without pre-generation. There is no build step and no storage for variants, at the cost of a per-transformation fee and a dependency on the CDN at request time. Setup of such a pipeline is covered in Building an Image CDN Pipeline for Static Sites.
Measured Impact
The same 600-post blog, Lighthouse 12 mobile preset, median of five runs on three post templates; build times on GitHub Actions.
| Measure | unoptimized | Build-time variants | Image CDN loader |
|---|---|---|---|
| Median hero transfer (mobile) | 780 KB | 64 KB | 48 KB |
| Image bytes per post page | 1.62 MB | 214 KB | 176 KB |
| Lab LCP | 3.1 s | 1.5 s | 1.4 s |
| Build time added | 0 | 4 min 10 s cold / 12 s warm | 0 |
| Output size | 410 MB | 1.3 GB | 410 MB |
| Monthly cost at 900k views | 0 | 0 | ~9 USD transformations |
The LCP Image Specifically
Whichever option, the hero image needs two extra attributes: priority on <Image> (which emits fetchpriority="high" and a preload in Next.js 14+) and an accurate sizes. Without sizes, the browser assumes the image is full viewport width and picks a larger file than needed; on the blog's two-column layout, adding sizes="(min-width: 1024px) 720px, 100vw" cut the desktop hero from the 1920 variant to the 960 variant. The effect of priority hints is measured in Optimizing LCP on Astro with Priority Hints, and applies equally to Next.js.
Check the choice in DevTools: the Network panel shows which variant each <img> requested, and currentSrc on the element in the console confirms it. A quick audit of every template at three viewport widths caught two other layouts — a card grid and an author avatar — where missing sizes had been fetching images four times larger than displayed.
Images Inside Markdown and MDX
Hero images rendered by templates are the easy case. Images inside post bodies — Markdown  syntax — bypass <Image> entirely unless you map them. With MDX, pass a components object mapping img to a wrapper that renders <Image> with the loader, reading dimensions from a manifest generated at build time (the sharp script can emit images.json with each source's width and height). Without dimensions, body images cause layout shift as they load, which undoes much of the benefit; the manifest approach supplies them without writers adding sizes by hand. On the blog, 3,900 body images went through this mapping, and CLS on long posts fell from 0.09 to 0.01 alongside the byte savings. For plain Markdown rendered with remark, a rehype plugin can rewrite <img> elements to <picture> with the generated variants in the same way.
Choosing Between Them
Build-time variants suit sites whose images live in the repository and change slowly: no runtime dependency, no per-request cost, and deploy-time certainty that every variant exists. The price is build time and output size, both manageable with a persistent cache. The CDN loader suits sites with many or frequently changing images, images from a CMS, or a CDN already in place: zero build cost and exact sizes, at a small usage fee. unoptimized is acceptable only for a handful of small, pre-optimised images — and then it is worth asking whether <Image> is needed at all versus a plain <img> with width, height and loading="lazy".
Pitfalls & Rollback
- Accepting
unoptimized: truepermanently. It fixes the build error by giving up responsive images. Treat it as a temporary step. - Missing
sizes. Without it,srcsetselection assumes full-width images and wastes bytes. - Regenerating every image on every build. Cache the output keyed by source hashes.
- Loader widths that do not exist. A build-time loader must only return widths that were generated; clamp to the generated list.
- Rollback: the loader is one config line; setting
unoptimized: trueagain restores the previous behaviour immediately.
Conclusion
A Next.js static export loses on-demand image optimisation, and the build's suggested fix — unoptimized: true — quietly ships original images to every device. Generating variants at build time or pointing a custom loader at an image CDN restores responsive, modern-format images. On a 600-post blog either approach cut image bytes per page by about 87% and lab LCP from 3.1 to about 1.5 seconds; pick build-time for repository images and zero runtime cost, the CDN for scale and flexibility.
FAQ
Why does next/image fail with output export?
The default image loader resizes images on request through Next.js's image optimisation API, which needs a running server. A static export has no server, so the build errors unless you set images.unoptimized to true or configure a custom loader.
Is images.unoptimized acceptable?
Only for sites with few, already-optimised images. It serves the original file at every viewport size, so a 2400-pixel hero reaches phones at full size. On our blog it doubled image bytes compared with a proper responsive setup.
What is the best option for a static export?
For most content sites, generating responsive variants at build time with a script or a package such as next-export-optimize-images. If an image CDN is already in use, a custom loader pointing at it is simpler and handles any size on demand.
Does this affect LCP?
Yes, often more than anything else on the page. Serving a right-sized AVIF or WebP instead of the original JPEG cut the hero image from 780 KB to 64 KB on mobile and moved lab LCP from 3.1 to 1.5 seconds in our tests.
Related
- Parent: Next.js Static Export for Content Sites — the export model and its limits.
- Next.js App Router Static Export Limitations — the other features that change under export.
- Building an Image CDN Pipeline for Static Sites — the CDN option in depth.
- Reducing LCP from Hero Images on Static Sites — the hero image beyond format and size.
- Next.js Static Export vs Astro for Marketing Sites — where Astro's built-in images compare.