Next.js Image Optimization Bill Spike: Cloudflare Loader & Sharp Fix

Stop runaway /_next/image transformation and Fast Origin Transfer bills on Vercel Pro ($0.06/1k) using Next.js 16 qualities, sharp WebP, or Cloudflare.

Checked 4 Dec 2026·Published 4 Dec 2026·9 min read·Raw .md
In brief
  • Lock down Next.js 16 next.config.mjs immediately with qualities: [75], pruned deviceSizes/imageSizes, minimumCacheTTL: 2678400 (31 days), and exact remotePatterns.
  • Remember that uncached /_next/image misses bill twice on Vercel Pro: $0.06 per 1,000 image transformations plus $0.06/GB Fast Origin Transfer above 10 GB.
  • Offload high-cardinality catalogs via a custom loaderFile to Cloudflare Images ($0.50/1k unique transforms after 5,000 free) or pre-generate static WebP with sharp for $0 runtime cost.

Why do Next.js /_next/image transformations multiply into surprise bills?

Default Next.js responsive srcset arrays generate up to 16 width variants per source image, and multiplying those widths across unpinned quality values, dual AVIF/WebP formats, short upstream TTLs, and bot crawlers turns a few thousand catalog images into millions of metered /_next/image requests. On Vercel Pro ($20/seat/mo), image transformations cost $0.06 per 1,000 transformations while uncached source fetches simultaneously burn your 10 GB Fast Origin Transfer allowance ($0.06/GB thereafter).

When an engineering team ships <Image src="/products/shoe.png" fill /> without auditing next.config.mjs, the HTML rendered to the browser does not contain a single image URL. Instead, Next.js emits a srcset spanning deviceSizes (historically [640, 750, 828, 1080, 1200, 1920, 2048, 3840]) and imageSizes ([16, 32, 48, 64, 96, 128, 256, 384] or the slightly trimmed Next.js 16 list). Every candidate points to the on-demand optimizer endpoint:

/_next/image?url=%2Fproducts%2Fshoe.png&w=1080&q=75

Look at the multiplicative math across a store or content site holding 4,000 source images:

  1. Width cardinality (16x): 8 deviceSizes + 8 imageSizes allow 16 distinct w= parameters per source URL.
  2. Quality fragmentation (3x–5x): Passing quality={80} on cards and quality={90} on heroes (or leaving qualities unrestricted) lets any queried q=1..100 spawn a separate transformation key.
  3. Format negotiation (2x): formats: ['image/avif', 'image/webp'] splits cache keys across AVIF and WebP Accept headers.
  4. Short upstream TTLs: When S3 or CMS origins send Cache-Control: max-age=300 without a high minimumCacheTTL, expired entries re-fetch and re-encode master files repeatedly.

Multiply 4,000 images × 16 widths × 3 qualities × 2 formats across two cache cycles, and a modest site hits 768,000 transformations before a single bot arrives. Once scrapers walk every srcset URL (see SEO-safe AI crawler & bot bill protection), three Vercel Pro meters fire together:

  • Image Transformations: $0.06 per 1,000 transformations.
  • Fast Origin Transfer: 10 GB included on Vercel Pro, then $0.06/GB. Fetching a 3.5 MB master PNG across 3,000 misses transfers 10.5 GB: crossing your free limit even with modest human traffic.
  • Fast Data Transfer: 1,000 GB (1 TB) included, then $0.15/GB for edge delivery.

Plug your catalog count and traffic into the Vercel vs Cloudflare Monthly TCO Calculator to see which meter crosses your $20 included usage credit first.

How do you lock down next.config.mjs to cut Vercel image bills by 80%+?

Restrict images.qualities to [75], cut deviceSizes and imageSizes down to 5–6 realistic breakpoints, pin minimumCacheTTL to 2678400 seconds (31 days), stick to ['image/webp'], and enforce exact remotePatterns paths. That single configuration diff shrinks valid transformation permutations per image by over 85% and blocks open-proxy abuse with HTTP 400 responses.

Next.js 16 tightened several image defaults (including introducing explicit images.qualities allowlists and localPatterns) specifically because unrestricted /_next/image query strings caused surprise invoices. Apply the hardened configuration below in next.config.mjs:

// next.config.mjs (Verified for Next.js 16+)
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    // 1. Reject arbitrary ?q=82 or ?q=100 probes with 400 Bad Request
    qualities: [75],

    // 2. Cut 16 default widths down to 6 practical responsive buckets
    deviceSizes: [640, 1080, 1920],
    imageSizes: [64, 128, 256],

    // 3. Single modern format avoids 2x AVIF+WebP split & high AVIF CPU cost
    formats: ['image/webp'],

    // 4. Floor cache lifetime at 31 days (2,678,400 seconds)
    minimumCacheTTL: 2678400,

    // 5. Lock local public assets and forbid query-string cache busting
    localPatterns: [
      {
        pathname: '/images/**',
        search: '',
      },
    ],

    // 6. Strict allowlist for remote storage — NEVER use hostname: '**'
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'media.example.com',
        port: '',
        pathname: '/catalog/**',
        search: '',
      },
    ],
  },
};

export default nextConfig;

Every setting closes a specific billing vector:

  • qualities: [75]: q=75 WebP is visually indistinguishable from q=90 on UI and photography at roughly half the byte weight, and blocks ?q=100 probes from spawning parallel cache keys.
  • 6 widths instead of 16: Mobile (640), retina mobile (1080), desktop (1920), and cards (64, 128, 256) cut srcset cardinality by 62.5%.
  • minimumCacheTTL: 2678400: Enforces a 31-day floor even when upstream buckets send weak Cache-Control headers, protecting Fast Origin Transfer. Always version immutable filenames (shoe-v2.png) instead of overwriting files in place.
  • search: '' on localPatterns and remotePatterns: Stops scrapers from appending ?cb=99182 inside url= to force cache misses.

Also audit JSX <Image fill> tags for missing sizes props; without sizes="(max-width: 768px) 100vw, 33vw", browsers assume 100vw and pull 1920px images for 320px cards.

When should you switch to a custom loaderFile with Cloudflare images or Workers?

Switch to a custom Next.js loaderFile backed by Cloudflare Images or R2 when your app serves heavy user-generated media, exceeds Vercel's 10 GB Fast Origin Transfer tier, or deploys outside Vercel entirely. Cloudflare Images includes 5,000 free unique 30-day transformations ($0.50/1k unique transforms thereafter), while Cloudflare Workers Static Assets ($5/mo Paid base) delivers static media at $0.00/GB egress.

Notice the subtle pricing model difference between Vercel Image Optimization and Cloudflare Images:

Architecture Base Plan Transform Meter Origin / Egress Meter Best Workload Fit
Vercel Pro (Default next/image) $20.00/seat/mo ($20 credit) $0.06 / 1,000 transforms (16 widths × qualities) 10 GB Fast Origin ($0.06/GB), 1 TB Fast Data ($0.15/GB) Small apps (<1,000 images) only if hardened
Vercel Pro (Hardened next.config.mjs) $20.00/seat/mo ($20 credit) $0.06 / 1,000 transforms (6 widths × q=75) Same meters, 80%+ fewer origin misses Dynamic Next.js SSR apps staying on Vercel
Next.js loaderFile + Cloudflare Images $5.00/mo Workers Paid (optional) 5,000 free unique / mo, then $0.50 / 1,000 unique (30d) $0.00/GB R2 origin fetch; CDN edge cached Large UGC / e-commerce catalogs (10k–500k assets)
Build-Time sharp WebP + Workers Static $5.00/mo Workers Paid $0.00 (zero runtime resizing) $0.00/GB static assets egress Marketing sites, docs, blogs, SaaS dashboards (<5k repo images)

Cloudflare bills per unique transformation per 30-day calendar window (defined by source origin + resize parameters), regardless of whether 50 or 5,000,000 edge PoP visitors view that resized image, and pairs cleanly with Cloudflare R2 ($0 egress between R2 and Cloudflare Images). However, at $0.50 per 1,000 unique transforms above the 5,000 free tier, sloppy width normalization on Cloudflare can also get expensive if you allow every pixel width.

Solve that permanently inside a custom loaderFile by snapping any requested width to four strict buckets before building the /cdn-cgi/image/ URL:

// lib/cloudflare-image-loader.js
const ALLOWED_WIDTHS = [256, 640, 1080, 1920];

function snapWidth(targetWidth) {
  for (const bucket of ALLOWED_WIDTHS) {
    if (targetWidth <= bucket) return bucket;
  }
  return ALLOWED_WIDTHS[ALLOWED_WIDTHS.length - 1];
}

export default function cloudflareImageLoader({ src, width, quality }) {
  // Serve raw files locally and never run vector SVGs through raster resizers
  if (process.env.NODE_ENV === 'development' || src.endsWith('.svg')) {
    return src;
  }

  const normalizedWidth = snapWidth(width);
  const pinnedQuality = quality ? Math.min(quality, 80) : 75;
  const cleanSrc = src.startsWith('/') ? src.slice(1) : src;

  const params = [
    `width=${normalizedWidth}`,
    `quality=${pinnedQuality}`,
    'format=auto',
    'fit=scale-down',
  ].join(',');

  return `https://media.example.com/cdn-cgi/image/${params}/${cleanSrc}`;
}

Wire it into next.config.mjs:

// next.config.mjs
const nextConfig = {
  images: {
    loader: 'custom',
    loaderFile: './lib/cloudflare-image-loader.js',
    deviceSizes: [640, 1080, 1920],
    imageSizes: [256],
  },
};

export default nextConfig;

Once loader: 'custom' is active, Next.js stops emitting /_next/image URLs completely. Your Vercel Image Optimization and Fast Origin Transfer image meters drop to zero. Also enable "Resize from within same zone only" (or an exact R2 origin list) in the Cloudflare Dashboard under Images -> Transformations so external domains cannot piggyback on /cdn-cgi/image/.

How do you eliminate runtime image metering entirely with Build-Time sharp WebP?

For blogs, documentation portals, landing pages, and static exports where images live in Git or sync at deploy time, pre-generate responsive .webp variants during your CI/CD build with sharp and map <Image> to static files via a 12-line custom loader. Runtime transformation fees, origin fetches, and cold-resize latency all become $0.00.

If you deploy a static Next.js build (output: 'export') to Cloudflare Workers Static Assets (see fixing Next.js static export trailing-slash 404s on Cloudflare Workers), runtime /_next/image is unavailable anyway, and setting images: { unoptimized: true } naively ships multi-megabyte source PNGs straight to mobile phones.

Instead, add a fast, incremental scripts/build-webp.mjs step using sharp (which Next.js already relies on natively):

// scripts/build-webp.mjs
import fs from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';

const SRC_DIR = path.resolve('assets/raw-images');
const OUT_DIR = path.resolve('public/gen-images');
const WIDTHS = [640, 1080, 1920];

async function walk(dir) {
  const entries = await fs.readdir(dir, { withFileTypes: true });
  const files = await Promise.all(
    entries.map((e) => {
      const full = path.join(dir, e.name);
      return e.isDirectory() ? walk(full) : full;
    })
  );
  return files.flat();
}

async function run() {
  const sources = (await walk(SRC_DIR)).filter((f) => /\.(png|jpe?g)$/i.test(f));

  for (const srcFile of sources) {
    const rel = path.relative(SRC_DIR, srcFile);
    const parsed = path.parse(rel);
    const meta = await sharp(srcFile).metadata();

    for (const w of WIDTHS) {
      const outPath = path.join(OUT_DIR, parsed.dir, `${parsed.name}-${w}w.webp`);
      await fs.mkdir(path.dirname(outPath), { recursive: true });

      // Skip re-encoding if output already exists and is newer than source
      try {
        const [srcStat, outStat] = await Promise.all([
          fs.stat(srcFile),
          fs.stat(outPath),
        ]);
        if (outStat.mtimeMs >= srcStat.mtimeMs) continue;
      } catch {
        // Output missing; generate below
      }

      const targetWidth = meta.width ? Math.min(meta.width, w) : w;
      await sharp(srcFile)
        .resize({ width: targetWidth, withoutEnlargement: true })
        .webp({ quality: 76, effort: 5 })
        .toFile(outPath);
    }
  }
}

run().catch((err) => {
  console.error(err);
  process.exit(1);
});

Pair that build artifact directory with lib/static-webp-loader.js:

// lib/static-webp-loader.js
const BUCKETS = [640, 1080, 1920];

export default function staticWebpLoader({ src, width }) {
  if (src.endsWith('.svg')) return src;
  const bucket = BUCKETS.find((b) => width <= b) ?? 1920;
  const withoutExt = src.replace(/\.(png|jpe?g|webp)$/i, '');
  const clean = withoutExt.startsWith('/') ? withoutExt.slice(1) : withoutExt;
  return `/gen-images/${clean}-${bucket}w.webp`;
}

Run node scripts/build-webp.mjs on a cheap ubuntu-latest (1x, $0.008/min) CI job, never inside a 10x macOS workflow (see stopping GitHub Actions macOS runner minute burns), and cache public/gen-images keyed on hashFiles('assets/raw-images/**'). On Cloudflare Workers Static Assets ($5/mo Paid plan), serving 50,000,000 hits against those pre-built .webp files incurs $0.00 in egress and $0.00 in Worker request charges.

How do you configure Vercel spend management hard caps and bot defenses?

Set an explicit monthly dollar budget in Vercel Spend Management with automated 50%, 75%, and 100% alerts, set immutable Cache-Control headers on upstream storage buckets, and block non-browser hotlinkers probing /_next/image directly. Hard caps turn an unbounded serverless meter into a predictable ceiling.

Treat billing caps as mandatory production guardrails:

  1. Enable Vercel Spend Management: Under Team Settings -> Billing -> Spend Management, set an overage budget (such as $40 above $20/seat) with 50%, 75%, and 100% email/webhook alerts, choosing whether 100% pauses traffic or alerts on-call while WAF rules throttle scrapers.
  2. Set Immutable Origin Headers: Upload source media with Cache-Control: public, max-age=31536000, immutable so S3/R2 buckets avoid revalidation loops and keep Fast Origin Transfer below 10 GB.
  3. Block External Hotlinking: In Cloudflare or Vercel Firewall, challenge /_next/image* requests carrying external Referer headers (not http.referer contains "example.com" and http.referer ne "").

Compare Fast Origin Transfer, Fluid Compute, and Workers costs in the Vercel vs Cloudflare Monthly TCO Calculator.

Production verification checklist before deploying your image fix

Verify your deployment with four curl checks against staging or preview URLs before closing the ticket: confirm allowed widths return 200 OK with image/webp and a long TTL, unlisted q or w values return 400 Bad Request, external URLs fail remotePatterns, and repeat requests hit edge cache.

Run these exact terminal checks against your preview deployment:

# 1. Valid bucketed width & pinned quality -> Expect HTTP/2 200, content-type: image/webp
curl -sI -H "Accept: image/avif,image/webp,*/*" \
  "https://preview.example.com/_next/image?url=%2Fimages%2Fhero.png&w=1080&q=75" \
  | grep -iE "^(http|content-type|cache-control|x-vercel-cache)"

# 2. Disallowed quality probe (?q=93) -> Expect HTTP/2 400 Bad Request in Next.js 16
curl -sI "https://preview.example.com/_next/image?url=%2Fimages%2Fhero.png&w=1080&q=93" \
  | head -n 5

# 3. Disallowed width probe (?w=999) -> Expect HTTP/2 400 Bad Request
curl -sI "https://preview.example.com/_next/image?url=%2Fimages%2Fhero.png&w=999&q=75" \
  | head -n 5

# 4. Open-proxy check -> Expect HTTP/2 400 Bad Request (blocks third-party origins)
curl -sI "https://preview.example.com/_next/image?url=https%3A%2F%2Fexample.org%2Ftest.png&w=640&q=75" \
  | head -n 5

Confirm that executing command #1 twice transitions x-vercel-cache: MISS (or cf-cache-status: MISS on custom Cloudflare loaders) to HIT on the second request. Once all three negative probes return 400 and valid assets return HIT, your image pipeline is locked against transformation multiplication.

Model your own stack numbersCalculate your real Vercel Pro, Cloudflare Workers, and CI/CD monthly TCO

Open Calculator →

Common edge cases

Why did my Vercel Fast Origin Transfer spike alongside Image Optimization?

Every time an edge PoP misses cache or generates a new /_next/image width and quality variant, the image optimizer fetches the original master asset from your origin or storage bucket. Vercel Pro includes only 10 GB of Fast Origin Transfer per month before billing $0.06/GB, so 3,500 misses on a 4 MB PNG already cross your free threshold.

Does setting images.unoptimized: true fix a Next.js image bill spike safely?

Setting unoptimized: true stops /_next/image transformation charges immediately, but serving raw 3 MB PNGs directly from Vercel burns through your 1 TB Fast Data Transfer allowance ($0.15/GB overage) and tanks Core Web Vitals LCP. Only use unoptimized: true if your source assets are already compressed responsive WebP files or served from a $0-egress CDN.

Can attackers abuse /_next/image if remotePatterns uses a wildcard hostname?

Yes. Configuring hostname: '**' turns your Next.js deployment into an open image-resizing proxy where third parties can pass arbitrary external URLs into /_next/image?url=https://... and bill the transformations, origin fetches, and egress directly to your account.

What changed1
  • 2026-12-04: Verified against December 2026 Next.js 16 image configuration, Vercel Fluid Compute/Origin Transfer meters, and GitHub Actions macOS runner multipliers.
Sources checked4

Spotted a provider quota or SDK change since 4 Dec 2026? Send a verification note →

Related troubleshooting runbooks