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' in next.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.

Three image strategies for a static export Three paths from a source image to the browser. Unoptimised: the original file is copied and served at every size. Build-time: a sharp script writes four widths in two formats into the export, and a custom loader picks the right one. Image CDN: the export references a CDN URL with width and format parameters, and the CDN transforms and caches on first request. Where resizing happens in each option hero.jpg 2400 px, 1.1 MB 0 · copy original 1 · sharp at build: 4 widths × 2 2 · loader → image CDN URL every device gets 1.1 MB phone gets 640 px WebP, 58 KB phone gets exact width AVIF, 41 KB Transfer sizes for a 390 px-wide phone at DPR 2, median post hero
Build-time generation moves the work into CI; the CDN option moves it to first request at the edge.

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.

MeasureunoptimizedBuild-time variantsImage CDN loader
Median hero transfer (mobile)780 KB64 KB48 KB
Image bytes per post page1.62 MB214 KB176 KB
Lab LCP3.1 s1.5 s1.4 s
Build time added04 min 10 s cold / 12 s warm0
Output size410 MB1.3 GB410 MB
Monthly cost at 900k views00~9 USD transformations
Image bytes and LCP by strategy Two groups of bars. Image bytes per post page: 1.62 megabytes unoptimised, 214 kilobytes with build-time variants, 176 kilobytes with a CDN loader. Lab LCP: 3.1 seconds, 1.5 seconds and 1.4 seconds. Unoptimised vs build-time vs CDN loader image KB per post 1,620 214 176 lab LCP (s) 3.1 1.5 1.4 unoptimized build-time CDN loader
Either real option removes seven eighths of the image bytes; the choice between them is about where you want the work and the cost.

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.

Effect of an accurate sizes attribute on the desktop hero On a 1440 pixel desktop viewport at DPR 1, without sizes the browser assumes the image fills the viewport and picks the 1920 pixel variant at 186 kilobytes. With sizes set to 720 pixels on wide screens, it picks the 960 pixel variant at 71 kilobytes, although the image occupies the same space on screen. Same slot on screen, different file chosen No sizes browser assumes 100vw → 1920 w · 186 KB sizes set 720 px slot → 960 w · 71 KB 1440 px viewport, DPR 1, two-column post layout
`sizes` tells the browser the slot before layout exists; without it, srcset selection guesses high.

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 ![alt](path) 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: true permanently. It fixes the build error by giving up responsive images. Treat it as a temporary step.
  • Missing sizes. Without it, srcset selection 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: true again 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.