PascalEugster

payloadcms plugin image optimizer

by PascalEugster
Media & images
v3
^3.0.0
MIT

Overview

Summary generated from the README

Adds the image features Payload does not ship natively, layered over its built-in sharp pipeline. It injects sensible defaults into the upload config of selected collections, such as WebP conversion, max dimensions and EXIF stripping. It also adds browser-side pre-resize, ThumbHash placeholders, filename strategies, an admin regeneration UI and Next.js display components. Requires Payload 3.37 or later, Next.js 14 or 15 and React 18 or 19.

Features

  • Canvas-based pre-resize in the browser before upload
  • ThumbHash blur placeholders with optional stored data URLs
  • Filename strategies: UUID, alt-text slug, timestamp or custom
  • Bulk regeneration UI with progress tracking and stop button
  • Admin sidebar panel showing original versus optimized size
  • ImageBox and FadeImage Next.js components with focal point support

Use cases

  • Shrink large camera photos in the browser before they reach upload limits on serverless hosts
  • Convert existing media libraries to WebP and reprocess them in bulk from the admin
  • Show instant blur-up previews on image-heavy Next.js listing pages

From the author

Payload CMS plugin: client-side pre-resize, ThumbHash blur placeholders, filename strategies, bulk regeneration UI, and Next.js display components — on top of Payload's native sharp pipeline

Installation

npm i @inoo-ch/payload-image-optimizer

27

Stars

2

Forks

2

Open Issues

2 days ago

Last Updated

549

Weekly Downloads

v3.5.4

npm Version

591.6 KB

Unpacked Size

1

Dependencies

GitHub stars

27+4 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 202627
Dec 4, 202627
Dec 3, 202627
Dec 2, 202627
Dec 1, 202627
Nov 30, 202627
Nov 29, 202627
Nov 28, 202627
Nov 27, 202627
Nov 26, 202627
Nov 25, 202627
Nov 24, 202627
Nov 23, 202627
Nov 22, 202627
Nov 21, 202627
Nov 20, 202627
Nov 19, 202627
Nov 18, 202627
Nov 17, 202627
Nov 16, 202627
Nov 15, 202627
Nov 14, 202627
Nov 13, 202627
Nov 12, 202627
Nov 11, 202627
Nov 10, 202627
Nov 9, 202627
Nov 8, 202627
Nov 7, 202627
Nov 6, 202627
Nov 5, 202627
Nov 4, 202627
Nov 3, 202627
Nov 2, 202627
Nov 1, 202627
Oct 31, 202627
Oct 30, 202627
Oct 29, 202627
Oct 28, 202627
Oct 27, 202627
Oct 26, 202627
Oct 25, 202627
Oct 24, 202627
Oct 23, 202627
Oct 22, 202627
Oct 21, 202627
Oct 20, 202627
Oct 19, 202627
Oct 18, 202627
Oct 17, 202627
Oct 16, 202627
Oct 15, 202627
Oct 14, 202627
Oct 13, 202627
Oct 12, 202627
Oct 11, 202626
Oct 10, 202626
Oct 9, 202625
Oct 8, 202625
Oct 7, 202625
Oct 6, 202625
Oct 5, 202625
Oct 4, 202625
Oct 3, 202625
Oct 2, 202625
Oct 1, 202625
Sep 30, 202624
Sep 29, 202624
Sep 28, 202624
Sep 27, 202624
Sep 26, 202624
Sep 25, 202624
Sep 24, 202624
Sep 23, 202624
Sep 22, 202624
Sep 21, 202624
Sep 20, 202624
Sep 19, 202624
Sep 18, 202624
Sep 17, 202623
Sep 16, 202623
Sep 15, 202623
Sep 14, 202623
Sep 13, 202623
Sep 12, 202623
Sep 11, 202623
Sep 10, 202623
Sep 9, 202623
Sep 8, 202623
Sep 7, 202623
Sep 6, 202623
npm weekly downloads

266−9 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 2026266
Dec 4, 2026230
Dec 3, 2026209
Dec 2, 2026231
Dec 1, 2026220
Nov 30, 2026228
Nov 29, 2026234
Nov 28, 2026275
Nov 27, 2026307
Nov 26, 2026362
Nov 25, 2026366
Nov 24, 2026367
Nov 23, 2026368
Nov 22, 2026358
Nov 21, 2026307
Nov 20, 2026267
Nov 19, 2026208
Nov 18, 2026286
Nov 17, 2026238
Nov 16, 2026240
Nov 15, 2026256
Nov 14, 2026260
Nov 13, 2026287
Nov 12, 2026381
Nov 11, 2026411
Nov 10, 2026507
Nov 9, 2026585
Nov 8, 2026664
Nov 7, 2026752
Nov 6, 2026758
Nov 5, 2026684
Nov 4, 2026660
Nov 3, 2026568
Nov 2, 2026494
Nov 1, 2026498
Oct 31, 2026478
Oct 30, 2026550
Oct 29, 2026509
Oct 28, 2026370
Oct 27, 2026479
Oct 26, 2026537
Oct 25, 2026536
Oct 24, 2026603
Oct 23, 2026479
Oct 22, 2026592
Oct 21, 2026842
Oct 20, 2026762
Oct 19, 2026795
Oct 18, 2026719
Oct 17, 2026612
Oct 16, 2026677
Oct 15, 2026630
Oct 14, 2026553
Oct 13, 2026658
Oct 12, 2026645
Oct 11, 2026689
Oct 10, 2026741
Oct 9, 2026792
Oct 8, 2026758
Oct 7, 2026725
Oct 6, 2026686
Oct 5, 2026611
Oct 4, 2026618
Oct 3, 2026784
Oct 2, 2026930
Oct 1, 2026918
Sep 30, 2026895
Sep 29, 2026799
Sep 28, 2026789
Sep 27, 2026743
Sep 26, 2026584
Sep 25, 2026421
Sep 24, 2026481
Sep 23, 2026704
Sep 22, 2026736
Sep 21, 20261,123
Sep 20, 20261,135
Sep 19, 20261,086
Sep 18, 20261,095
Sep 17, 20261,075
Sep 16, 20261,018
Sep 15, 2026997
Sep 14, 2026632
Sep 13, 2026792
Sep 12, 2026742
Sep 11, 2026704
Sep 10, 2026659
Sep 9, 2026521
Sep 8, 2026500
Sep 7, 2026478
Sep 6, 2026275

Each point is npm's rolling 7-day download count.

Health Score

79/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1183370159-root.svg)](https://payloaddirectory.dev/plugins/1183370159-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1183370159-root"><img src="https://payloaddirectory.dev/badge/1183370159-root.svg" alt="Payload Directory"></a>
Updated Dec 3, 2026Created Mar 16, 2026Published Dec 3, 2026

README

@inoo-ch/payload-image-optimizer

npm version npm downloads GitHub

A Payload CMS plugin that adds the pieces Payload doesn't ship: client-side pre-resize, ThumbHash blur placeholders, filename strategies, bulk regeneration UI, and Next.js display components — layered on top of Payload's own sharp pipeline.

Built and maintained by inoo.ch — a Swiss digital agency crafting modern web experiences.

What This Plugin Adds

Payload 3.x already ships with sharp and exposes formatOptions, resizeOptions, imageSizes, and withMetadata — so format conversion, resize, per-size variants, focal-point-aware cropping, and EXIF stripping are all achievable natively. This plugin does not replace any of that. It injects sensible defaults onto your collection's upload config and then adds the things Payload genuinely doesn't do.

Things Payload can already do (the plugin just sets sensible defaults)

  • Convert originals + per-size variants to WebP (or AVIF) — via upload.formatOptions and per-imageSize.formatOptions
  • Resize to max dimensions — via upload.resizeOptions
  • Strip EXIF — via upload.withMetadata: false
  • Focal-point-aware cropping for imageSizes
  • Admin crop / focal-point UI

Prefer to wire those yourself? You don't need this plugin for any of them.

Things Payload does not do out of the box

  • Client-side pre-resize — Canvas-based resize in the browser before the file hits the network. Cuts 12MB DSLR photos to ~100–500KB pre-upload. Particularly important with clientUploads: true (Vercel Blob), where the server-side sharp pipeline is bypassed entirely.
  • ThumbHash blur placeholders — Tiny base64 hashes generated per image for instant blur-up previews. Opt-in storeBlurDataURL additionally pre-decodes the hash into its base64 PNG data URL at upload time, so rendering components can skip the per-render thumbHashToDataURL decode.
  • Filename strategies — Top-level generateFilename callback (Payload only exposes per-imageSize.generateImageName, not a parent-level one). Built-ins: uuidFilename (avoids Vercel Blob "already exists"), seoFilename (alt-text → slug), timestampFilename.
  • Bulk regeneration UI — One-click reprocess-all or reprocess-unoptimized from the admin, with progress tracking, stop button, and a REST API.
  • Optimization status panel — Admin sidebar showing original vs. optimized size, savings %, and blur preview.
  • Next.js display components — <ImageBox> and <FadeImage> wrappers with ThumbHash blur, fade-in, focal point, and a responsive variant loader that serves pre-generated imageSizes variants directly (bypassing /_next/image re-optimization).
  • Template integration helper — getOptimizedImageProps() adds ThumbHash + focal point + variant loader to the Payload website template's <NextImage> in 3 lines.

Requirements

  • Payload CMS ^3.37.0
  • Next.js ^14.0.0 or ^15.0.0
  • React ^18.0.0 or ^19.0.0
  • Node.js ^18.20.2 or >=20.9.0

Installation

pnpm add @inoo-ch/payload-image-optimizer
# or
npm install @inoo-ch/payload-image-optimizer
# or
yarn add @inoo-ch/payload-image-optimizer

Note: This plugin uses sharp for image processing. It is expected as a peer dependency from Payload CMS — no separate install needed.

Quick Start

Add the plugin to your payload.config.ts:

import { buildConfig } from 'payload'
import { imageOptimizer } from '@inoo-ch/payload-image-optimizer'

export default buildConfig({
  // ...
  plugins: [
    imageOptimizer({
      collections: {
        media: true,
      },
    }),
  ],
})

That's it. Every image uploaded to the media collection is resized to 2560×2560, converted to WebP, stripped of EXIF, and gets a ThumbHash placeholder.

Configuration

Full Example

imageOptimizer({
  collections: {
    media: {
      format: { format: 'webp', quality: 90 },
      maxDimensions: { width: 4096, height: 4096 },
    },
    avatars: true, // uses global defaults
  },

  // Global defaults (per-collection config overrides these)
  format: { format: 'webp', quality: 80 },  // null disables format conversion entirely
  maxDimensions: { width: 2560, height: 2560 },
  generateThumbHash: true,
  stripMetadata: true,
  clientOptimization: true,
  disabled: false,

  // Optional config-injection helpers (all opt-in, all honor user-set upload values)
  adminThumbnail: 'auto',         // function form survives .jpg → .webp parent rename
  // responseHeaders: 'immutable', // long-lived Cache-Control; pair with `generateFilename`
  // metadataPolicy: ({ metadata }) => metadata.format === 'jpeg', // richer than stripMetadata
})

Options

OptionTypeDefaultDescription
collectionsRecord<string, true | CollectionConfig>requiredCollections to optimize. Use true for defaults or an object for overrides.
formatFormatQuality | null{ format: 'webp', quality: 80 }Target format and quality (1-100). Pass null to disable format conversion (keep original extension).
maxDimensions{ width: number, height: number }{ width: 2560, height: 2560 }Maximum image dimensions. Images are resized to fit within these bounds.
generateThumbHashbooleantrueGenerate ThumbHash blur placeholders for instant image previews.
storeBlurDataURLbooleanfalseOpt-in: pre-decode the ThumbHash into its base64 PNG data URL at upload time and persist it as imageOptimizer.blurDataURL, so getImageOptimizerProps() skips the per-render thumbHashToDataURL decode. Trades ~1–3 KB extra per media doc (on disk and in every listing-endpoint response) for less client-side JS work on image-heavy pages. Back-compatible: existing docs uploaded before the flag was set continue to render via the runtime-decode fallback. See Pre-decoded blur data URLs.
stripMetadatabooleantrueSets upload.withMetadata: false AND guarantees sharp runs on every upload (Payload skips sharp entirely when no transform is configured, which preserves EXIF). Use metadataPolicy for richer control.
generateFilename(args) => string—Custom filename stem generator. Built-ins: uuidFilename (UUID — prevents Vercel Blob "already exists" errors), seoFilename (human-readable from alt text), timestampFilename (original filename stem + ISO timestamp with ms). Note: all filename strategies only work with server-side uploads (Payload default, clientUploads: false). With clientUploads: true the blob pathname is locked client-side before server hooks run, so generateFilename is effectively ignored — use addRandomSuffix: true on the storage adapter instead. See Filename strategies and client uploads.
clientOptimizationbooleantruePre-resize images in the browser before upload using Canvas API. Reduces upload size by up to 90% for large images.
regenerateButtonboolean | { enabled?: boolean, allowForceAll?: boolean }trueControls the regeneration UI. false hides it entirely. Pass an object to opt in to the Force re-process all checkbox (allowForceAll: true) — off by default so the primary action is always "Regenerate N Unoptimized".
adminThumbnail'auto' | string | function'auto'Injects an upload.adminThumbnail on each targeted collection. 'auto' picks the smallest pre-generated doc.sizes entry (avoids downloading the full parent into a 50-px list row) and falls back to /api/{slug}/file/{filename} — surviving the .jpg → .webp parent-extension change. String mode is treated as a size-name reference; function mode is passed through. Respects user-set values.
responseHeadersfalse | 'immutable' | functionfalseOpt-in upload.modifyResponseHeaders injection. 'immutable' sets Cache-Control: public, max-age=31536000, immutable — only safe with content-stable filenames (generateFilename); otherwise the plugin warns at init. Function mode is passed through. Respects user-set values.
metadataPolicy({ metadata }) => boolean | Promise<boolean>—Richer alternative to stripMetadata. When set, passed through as withMetadata (return true to keep, false to strip). Takes precedence over stripMetadata. Respects user-set values.
regenerateUseTransactionsbooleanfalseWhether the regeneration task wraps its payload.update({ file }) in a MongoDB transaction. Defaults to false — the sharp + cloud-storage upload pipeline on large originals routinely exceeds MongoDB's default transactionLifetimeLimitSeconds (60s), causing a transaction abort that cascades into the error writeback. Running non-transactionally sidesteps that ceiling. Set to true only if you've bumped your cluster's transaction lifetime and prefer atomicity per regen. The error-status writeback is always non-transactional regardless of this setting, so the doc's imageOptimizer.status = 'error' is reliably persisted on failure.
disabledbooleanfalseDisable optimization while keeping schema fields intact.

Per-Collection Overrides

Each collection can override format and maxDimensions:

collections: {
  // Hero images: higher quality, larger dimensions
  heroes: {
    format: { format: 'webp', quality: 95 },
    maxDimensions: { width: 3840, height: 2160 },
  },
  // Thumbnails: more aggressive compression
  thumbnails: {
    format: { format: 'webp', quality: 60 },
    maxDimensions: { width: 800, height: 800 },
  },
}

Pre-decoded blur data URLs

getImageOptimizerProps() normally runs thumbHashToDataURL on every render to turn a stored ThumbHash into a base64 PNG data URL. That helper is a JS-native inverse-DCT + manual Deflate/CRC/base64 PNG build — plugin consumers have observed empirically that each call costs roughly 1–5 ms per image on mid-tier Android. On listing pages with 20+ media items this can show up as measurable TBT.

Setting storeBlurDataURL: true moves the decode to upload time:

imageOptimizer({
  collections: { media: true },
  storeBlurDataURL: true,
})

When enabled, the imageOptimizer group gains a hidden, read-only blurDataURL text field. beforeChange pre-decodes the ThumbHash once per upload via the plugin's internal decodeThumbHashToDataURL() helper and persists the result. getImageOptimizerProps() then prefers the stored value and skips the per-render decode.

When to turn it on: listings with many media items where you've observed client-side decode cost is non-trivial, and where the extra payload bytes are not a concern. Measure before flipping the flag — no benchmark has been run inside this plugin yet.

When to leave it off: listing endpoints that return hundreds of media docs per request, where the ~1–3 KB/doc of extra wire payload matters more than the client-side decode it would save. The flag is off by default for this reason.

Back-compat: flipping the flag on an existing site activates the new code path for new uploads. Old docs uploaded before the flag was set continue to render correctly via the runtime-decode fallback. To backfill them, click Regenerate All Documents in the admin collection list (or hit POST /api/image-optimizer/regenerate) — the regeneration task already re-runs beforeChange, so every processed doc gets the field populated. No new endpoint was added.

Client-Side Optimization

When clientOptimization: true is set, images are pre-resized in the browser before uploading. This uses the Canvas API (zero additional dependencies) to shrink large images to fit within maxDimensions before they enter the upload pipeline.

imageOptimizer({
  clientOptimization: true,
  collections: { media: true },
})

How it helps:

  • A 12MB DSLR photo is resized to ~100-500KB before upload — 90%+ less data transferred
  • Especially important with cloud storage + clientUploads: true, where files round-trip through blob storage
  • Reduces serverless function processing time (smaller input = faster sharp conversion)
  • EXIF metadata is stripped automatically (Canvas output has no metadata)

What stays server-side: Format conversion (WebP/AVIF), ThumbHash generation, and per-size variant creation still happen on the server with sharp for quality consistency. The client only handles resize — the highest-impact optimization with zero quality trade-off.

Save-button behavior: While the client-side resize is running, the Save button is disabled and an "Optimizing image…" spinner appears below the uploader. Status is reset on completion, error, and unmount. The hint is localized via the plugin-imageOptimizer:optimizing i18n key (en / de / fr included).

Limitations: Only applies to single-file uploads in the admin panel. Bulk uploads and API/programmatic uploads are processed server-side as usual.

Logging

The imageOptimizer_regenerateDocument task emits structured Pino records through req.payload.logger. Every record carries a stable event field for log-aggregator filtering and errors are serialized as { err } so Pino's standard error serializer captures name/message/stack/cause.

imageOptimizer({
  collections: { media: true },
  logging: 'silent', // default — errors only
})
Modeenter / exitErrorsDoc details on exitSkips logged
'silent' (default)—error——
'normal'infoerror—user-cancelled
'verbose'infoerrorfilename / alt / mimeType / filesizeall reasons

For fine-grained control, pass an object. It merges over the 'silent' baseline:

imageOptimizer({
  collections: { media: true },
  logging: {
    lifecycle: true,                // info enter/exit per job
    errors: true,                   // default — set false to suppress
    includeDocDetails: false,
    skips: { userCancelled: true }, // or `true` / `false` shorthand for all reasons
  },
})

Event tags (stable — grep these):

  • imageOpt.regen.enter — job start, before the cancellation check.
  • imageOpt.regen.exit — job complete. Always carries durationMs.
  • imageOpt.regen.skipped — terminal skip. reason is user-cancelled, doc-deleted, or not-image.
  • imageOpt.regen.error — thrown inside the handler. Emitted before the status writeback, so the stack is captured regardless of whether the writeback itself succeeds.
  • imageOpt.regen.writebackFailed — the error-status writeback itself failed (secondary diagnostic; rare).

Errors are emitted in every mode unless explicitly disabled (logging: { errors: false }). The steady-state cost of 'silent' mode is zero log lines on the success path.

How It Works

  1. Plugin init — The plugin resolves your options and injects them as native upload-config (upload.formatOptions, upload.resizeOptions, upload.withMetadata, and per-imageSize formatOptions) on each targeted collection.
  2. Upload — Payload's own generateFileData() runs your image through sharp once: resize to maxDimensions, convert to your target format (e.g. WebP), strip metadata, generate every imageSize variant.
  3. beforeOperation hook — Captures the pre-pipeline file size so the savings metric is accurate.
  4. beforeChange hook — Stamps the imageOptimizer group (originalSize / optimizedSize / status / ThumbHash) and applies your optional filename strategy. Always resolves synchronously — status is 'complete' immediately.
  5. Done — The document is saved exactly once. No async jobs, no post-save follow-ups.

This delegates the heavy lifting to Payload's native pipeline. The plugin adds one sharp decode for ThumbHash generation (100×100 raw) and nothing else.

Vercel / Serverless Deployment

Image processing (especially AVIF encoding and metadata stripping) can exceed the default serverless function timeout. Set maxDuration as a literal in your Payload API route:

// src/app/(payload)/api/[...slug]/route.ts
export const maxDuration = 300

This sets a 300-second timeout, which covers large-file regenerations (source download, sharp processing, re-upload to cloud storage).

Don't re-export it (export { maxDuration } from '@inoo-ch/payload-image-optimizer'): since Next.js 16.5 the build fails with "Next.js can't recognize the exported maxDuration field in route. It mustn't be reexported." Route segment config must be a literal in the route file.

Large file uploads with Vercel Blob

Even with maxDuration and bodySizeLimit configured, large file uploads through the Payload admin still go through the Next.js API route, which hits Vercel's request body size limit (4.5MB on serverless functions). The plugin's client-side pre-resize (clientOptimization, on by default) keeps most photos under that limit — but raw DSLR RAWs, videos, or other non-resizable media can still exceed it. For those, @payloadcms/storage-vercel-blob supports clientUploads:

vercelBlobStorage({
  collections: { media: true },
  token: process.env.BLOB_READ_WRITE_TOKEN,
  clientUploads: true, // uploads go directly from browser to Vercel Blob (up to 5TB)
})

Read this before enabling clientUploads: true — it has real trade-offs:

With clientUploads: true, the browser PUTs the file directly to Vercel Blob using a signed URL. The server never sees the bytes until the metadata POST, at which point the blob already exists under the filename the browser chose. That breaks every server-side transformation that would normally own the filename or the blob contents:

What you lose with clientUploads: trueWhy
seoFilenameAlt text isn't available at sign time; the pathname is locked before any server hook runs
Server-side format conversion (upload.formatOptions)The optimized buffer is computed but never written — Vercel Blob keeps the browser's original bytes
Server-side resize (upload.resizeOptions)Same reason — server processes the buffer in memory, discards the result
EXIF stripping on the originalSame reason (per-size variants are still stripped, since those run through generateFileData)

This is a Payload + storage-vercel-blob architectural constraint, not a plugin limitation — the cloud-storage adapter explicitly skips handleUpload when clientUploadContext is set.

Filename strategies and client uploads
Upload modeWorks withRecommended
clientUploads: false (Payload default)uuidFilename, seoFilename, custom generateFilenameseoFilename for SEO; uuidFilename for immutable caching
clientUploads: trueuuidFilename via addRandomSuffix: true on the storage adapteraddRandomSuffix: true — filenames become photo-a1b2c3.jpg

With clientUploads: true, your imageOptimizer({ generateFilename }) is still called (it runs in beforeChange like always), but any rename it produces will make data.filename diverge from the actual blob pathname — resulting in 404s. So do not combine clientUploads: true with generateFilename. Use the storage adapter's addRandomSuffix instead:

vercelBlobStorage({
  collections: { media: true },
  token: process.env.BLOB_READ_WRITE_TOKEN,
  clientUploads: true,
  addRandomSuffix: true, // photo.jpg → photo-a1b2c3.jpg (added at sign time, client is told the final name)
})
"This blob already exists" error (server-side uploads only)

This only applies when clientUploads is off (the default). When a format is configured (the default), the plugin changes filenames during upload (e.g., photo.jpg → photo.webp). If a blob with that name already exists, Vercel Blob throws an error because @payloadcms/storage-vercel-blob does not pass allowOverwrite to the Vercel Blob SDK.

Fix: Set generateFilename: uuidFilename — replaces original filenames with UUIDs before the storage adapter sees them:

import { imageOptimizer, uuidFilename } from '@inoo-ch/payload-image-optimizer'

imageOptimizer({
  collections: { media: true },
  generateFilename: uuidFilename, // photo.jpg → a1b2c3d4-5e6f-7890-abcd-ef1234567890.webp
})

This prevents collisions on both initial uploads and bulk regeneration. Payload stores the full URL in the database, so UUID filenames are transparent to your application.

Prefer human-readable names? generateFilename: seoFilename slugifies the alt text (e.g., Edelstahl Geländer → edelstahl-gelaender-1745123456.webp). Only works with server-side uploads.

How It Differs from Payload's Default Image Handling

Payload CMS ships with sharp and exposes every sharp knob you need — upload.formatOptions, upload.resizeOptions, upload.withMetadata, per-imageSize formatOptions, focal-point-aware cropping — so the bulk of "image optimization" is native. This plugin resolves your options and injects them onto Payload's upload config at init time, then lets generateFileData() do the encoding. The plugin's value is the layer around that pipeline: client-side pre-resize, ThumbHash, filename strategies, the regeneration UI, and the Next.js display components.

Comparison

CapabilityPayload DefaultWith This Plugin
Resize to max dimensionsupload.resizeOptions (per collection)Same, via one config block with global default + per-collection override
WebP/AVIF conversionupload.formatOptions / per-size formatOptions — repeat per collectionSingle config covers parent file + all sizes
EXIF metadata strippingSharp strips by default (withMetadata: false) only when sharp runsGuaranteed — plugin's injected resizeOptions/formatOptions always triggers sharp
Focal-point-aware cropsNative (upload.focalPoint)Unchanged — native Payload handles this
Filename strategiesPer-size generateImageName onlyTop-level generateFilename (seoFilename / uuidFilename / timestampFilename / custom)
Blur hash placeholdersNot supportedThumbHash generated per image
Client-side pre-resizeNot supportedCanvas-based resize in browser before upload
Optimization status & savingsNot supportedAdmin sidebar panel per image
Bulk re-process existing imagesNot supportedOne-click regeneration with progress + stop button
Next.js <Image> with blur + focal pointManual wiringDrop-in <ImageBox> / getOptimizedImageProps()

Native edge cases this plugin handles for you

  • withoutEnlargement silent drop — Payload's native default (undefined) silently omits any imageSize where both dimensions are smaller than the target (the size appears as { filename: null } in the doc). The plugin sets withoutEnlargement: true so small uploads keep a usable variant.
  • Per-size formatOptions does not inherit — Native imageSize.formatOptions does not inherit from upload.formatOptions; each size would need repeating. The plugin injects the primary format onto every size automatically.
  • Sharp-skip EXIF leak — If no formatOptions/resizeOptions/trimOptions is set and the image is not animated, native Payload skips sharp entirely and writes the original bytes (EXIF intact). The plugin's injected resizeOptions + formatOptions guarantee sharp always runs, closing this gap.

CPU & Resource Impact

  • Single-pass pipeline — Metadata stripping, resize, and format conversion run in Payload's single sharp pipeline — one decode/encode cycle.
  • ThumbHash — One additional sharp pass (100×100 raw buffer) per upload. Negligible.
  • No background jobs on upload — As of v3, every upload resolves synchronously. The only async workload is bulk regeneration (which only runs when you click it).
  • Bulk regeneration runs in parallel waves — 20 images per wave by default — on a dedicated image-optimizer job queue that doesn't interfere with other consumers of Payload's default queue. The POST endpoint returns immediately after queueing; progress happens in the background (waitUntil on Vercel, or Payload autorun on hosts that have it configured). Each run respects a 270-second wall-clock budget so serverless timeouts don't cut off jobs mid-upload — anything still pending when the budget exhausts stays queued for autorun or the next regenerate click (which only picks up still-pending docs).

Admin UI

The plugin adds an Optimization Status panel to the document sidebar showing:

  • Status badge (complete / error)
  • Original vs. optimized file size with savings percentage
  • ThumbHash blur preview thumbnail
  • Regenerate this image button to re-run optimization on the current document only

A Regenerate button also appears in collection list views. By default it targets only unoptimized images (label reads Regenerate N Unoptimized, or All images optimized when nothing is pending). Selecting rows scopes it to just those. The full-collection "Force re-process all" opt-in is hidden unless you enable it via regenerateButton: { allowForceAll: true }.

Displaying Images

Import from /frontend, not /client. The frontend entry point (@inoo-ch/payload-image-optimizer/frontend) exports only display helpers (ImageBox, FadeImage, getOptimizedImageProps, getImageOptimizerProps, createVariantLoader) and has zero dependency on @payloadcms/ui. Importing from /client on a public page works but drags the admin UI into your frontend bundle under Turbopack. The /client barrel is kept for Payload's importMap and backward compatibility.

Option 1: ImageBox (New Projects)

Drop-in Next.js <Image> wrapper — the easiest way to display images with best practices:

import { ImageBox } from '@inoo-ch/payload-image-optimizer/frontend'

// Hero image — fill mode with priority
<ImageBox media={doc.heroImage} alt="Hero" fill priority />

// Card grid — explicit sizes hint
<ImageBox media={doc.image} alt="Card" fill sizes="(max-width: 768px) 100vw, 33vw" />

// Fixed dimensions
<ImageBox media={doc.avatar} alt="Avatar" width={64} height={64} fade={false} />

What it does automatically:

  • Per-image ThumbHash blur placeholder
  • Smooth blur-to-sharp fade transition
  • Focal point positioning from focalX/focalY
  • Responsive variant loader — serves pre-generated Payload size variants directly instead of /_next/image re-optimization (when imageSizes is configured on the collection)
  • Smart sizes default for fill mode — (max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw instead of the browser's 100vw assumption
  • Cache busting via updatedAt

Option 2: getOptimizedImageProps() (Existing Projects / Payload Website Template)

If you're using the Payload website template or have an existing <NextImage> component, add 3 lines:

import { getOptimizedImageProps } from '@inoo-ch/payload-image-optimizer/frontend'

const optimizedProps = getOptimizedImageProps(resource)

<NextImage
  {...optimizedProps}   // ThumbHash blur, focal point, variant loader
  src={src}
  alt={alt}
  fill={fill}
  sizes={sizes}
  quality={80}
/>

This replaces the template's hardcoded blur placeholder with per-image ThumbHash, adds focal point support, and enables responsive variant loading.

Responsive Variant Loading

When your collection has imageSizes configured (e.g., thumbnail: 300, medium: 900, large: 1400), both ImageBox and getOptimizedImageProps() automatically create a hybrid next/image loader that:

  1. Picks the smallest pre-generated variant >= the requested width
  2. Serves it directly from your storage (bypasses /_next/image — no double optimization)
  3. Falls back to /_next/image when no close variant match exists

This means images uploaded to collections with imageSizes get responsive loading for free — no extra config needed.

Document Schema

The plugin adds an imageOptimizer field group to each configured collection:

{
  imageOptimizer: {
    status: 'complete' | 'error',
    originalSize: number,    // bytes
    optimizedSize: number,   // bytes
    thumbHash: string,       // base64-encoded ThumbHash
    error: string,           // error message (if failed)
  },
}

REST API Endpoints

Start Bulk Regeneration

POST /api/image-optimizer/regenerate
Content-Type: application/json

{ "collectionSlug": "media", "force": false }
  • force: false — only regenerates images that are not yet complete
  • force: true — re-processes all images from scratch (only honored when regenerateButton.allowForceAll: true)

Response: { "queued": 42, "collectionSlug": "media" }

Check Regeneration Progress

GET /api/image-optimizer/regenerate?collection=media

Response: { "collectionSlug": "media", "total": 42, "complete": 30, "errored": 1, "pending": 11, "cancelled": false }

Cancel In-Flight Regeneration

DELETE /api/image-optimizer/regenerate
Content-Type: application/json

{ "collectionSlug": "media" }

All endpoints require an authenticated user.

Upgrading from v2.x

v3 is a breaking release. See MIGRATION.md for a full migration guide. In short:

  • formats: FormatQuality[] → format: FormatQuality | null (singular). Only one format per collection.
  • replaceOriginal removed. When format is set, the original is always replaced (via Payload's native upload.formatOptions).
  • imageOptimizer.variants field removed. Additive multi-format variants (e.g. WebP+AVIF siblings) are no longer a feature — they only worked on local disk, never on cloud storage.
  • imageOptimizer.status enum is now 'complete' | 'error' (no more 'pending' / 'processing').

AI Agent Integration

Full technical documentation for AI coding agents is available in AGENT_DOCS.md. It covers all configuration options, field schemas, endpoints, client utilities, background jobs, and context flags in a single reference file.

Prompt for AI Agents

Copy-paste this instruction to your AI coding agent to have it autonomously integrate the plugin:

Install @inoo-ch/payload-image-optimizer and integrate it into this Payload CMS project. Read node_modules/@inoo-ch/payload-image-optimizer/AGENT_DOCS.md for the full API reference. Based on the project's existing upload collections and frontend, decide on your own:

  1. Which upload collections should be optimized and with what settings (format, maxDimensions)
  2. For new components: use <ImageBox> — it handles ThumbHash blur, fade-in, focal point, responsive variant loading, and smart sizes defaults automatically
  3. For existing components (especially the Payload website template's ImageMedia): use getOptimizedImageProps(resource) — a single spread that adds ThumbHash, focal point, and variant loader to any <NextImage>
  4. If collections have imageSizes configured, the variant loader will automatically serve pre-generated size variants directly instead of going through /_next/image re-optimization

Use the zero-config default (collections: { <slug>: true }) unless the project has specific requirements that call for custom settings.

Contributing

This plugin is open source and we welcome community involvement:

  • Issues — Found a bug or have a feature request? Open an issue.
  • Pull Requests — PRs are welcome! Please open an issue first to discuss larger changes.

All changes are reviewed and merged by the package maintainer at inoo.ch.

License

MIT - inoo.ch

Similar plugins