@next/safe-image-optimization
v0.0.2
Published
A safer image optimization library for Node.js, built on memory-safe Rust decoders
Readme
@next/safe-image-optimization
An image optimization library for Node.js, built for Next.js's image optimizer (next/image).
Usage
const { defaultPool } = require('@next/safe-image-optimization')
const output = await defaultPool()
.prepare(input)
.allowInputFormats(['jpeg', 'png', 'webp', 'avif'])
.limitInputPixels(268402689)
.timeoutMs(10_000)
.autoOrient() // using EXIF metadata
.resize(640, null, { withoutEnlargement: true })
.webp({ quality: 75 })
.toBuffer({ signal: request.signal }) // abort if the client disconnectsTo read an image's format and dimensions without decoding its pixels:
const meta = await defaultPool().prepare(input).timeoutMs(5_000).metadata()
// {
// format: 'jpeg',
// width: 1920,
// height: 1080,
// hasAlpha: false,
// orientation: 1,
// hasProfile: true,
// autoOrient: { width: 1920, height: 1080 },
// }Supported formats and operations
- Input formats: JPEG, PNG, WebP, GIF, TIFF, AVIF, and SVG (in-memory
Buffer, typed array, orArrayBufferonly). SVG must be allowed explicitly with.allowInputFormats(). - Output formats: JPEG (
.jpeg()), PNG (.png()), WebP (.webp()), and GIF (.gif()). Output is always 8-bit sRGB with metadata stripped. - Operations:
.autoOrient(): orient using EXIF metadata..rotate(angle): rotate by a multiple of 90° (after.autoOrient(), if it's also called)..resize(width, height, options): resize while preserving aspect ratio (cropping from the center when both width and height are given), withwithoutEnlargement,withoutReduction, andkerneloptions.
- Input restrictions and limits (
0removes a limit):.allowInputFormats(formats)restricts which formats are accepted (detected from the file contents)..animated('reject')rejects animated images withERR_ANIMATEDbefore decoding. With.animated('first-frame')(the default), only the first frame is decoded..limitInputPixels(),.limitAllocatorMemoryBytes(), and.limitOutputBytes()bound image dimensions, memory use, and output size..timeoutMs(ms)cancels processing if an image takes too long. There is no default timeout, so you should set one when handling untrusted images.
- Cancellation:
.toBuffer({ signal })and.metadata({ signal })accept anAbortSignal. - Errors: Processing errors throw a
SafeImageOptimizationErrorwith a stablecodeproperty (such asERR_UNSUPPORTED_FORMAT,ERR_LIMIT_EXCEEDED, orERR_TIMEOUT). Invalid options throw aTypeErrorwith the codeERR_INVALID_OPTIONS.
Worker pools
Images are processed in a pool of background workers, one image per worker at a time. Workers start on demand, and by default, each one is replaced after processing a single image (except on Windows; see maxImagesPerWorker). Workers are also replaced if they crash or time out. With maxImagesPerWorker above 1, they're reused, and exit after idleTimeoutMs without work.
defaultPool() returns a shared pool sized to os.availableParallelism(). You can also create a pool with custom settings:
const { Pool } = require('@next/safe-image-optimization')
const pool = new Pool({
concurrency: 4,
maxImagesPerWorker: 16,
idleTimeoutMs: 30_000,
})
const output = await pool.prepare(input).timeoutMs(10_000).webp().toBuffer()Idle workers don't keep the process alive, so pools don't need to be closed. To stop a pool's workers, await pool.close() finishes the images already submitted first, and await pool.destroy() stops them immediately. await using pool = new Pool() closes the pool at the end of the scope.
Purpose
sharp (built on libvips) is a fast, general-purpose image processing library with a broad set of features. @next/safe-image-optimization has a similar chainable API so it is familiar to use, but it is built around different goals:
- Focused scope: It implements only the small set of operations needed for Next.js's image optimizer and ImageResponse.
- Designed for untrusted input: Web servers often optimize images uploaded by users or fetched from remote URLs. This library decodes images using memory-safe Rust libraries inside separate, sandboxed worker processes (or WebAssembly worker threads) with per-image memory and time limits. If an image triggers a bug, exceeds its memory budget, or times out, only that worker stops—the main Node.js process continues running unaffected.
Because of these goals, @next/safe-image-optimization has a much smaller feature set than sharp and trades some performance for isolation. packages/bench measures that trade, against sharp and @napi-rs/image.
While this library is designed to protect against untrusted input, it may still have vulnerabilities. You should only fetch remote images from trusted sources or your own object storage. Use Next.js's images.remotePatterns configuration to restrict allowed image sources.
Documentation
- Safety model — decoders, worker isolation, sandboxing, and resource limits
- Differences from sharp — API, operation, and format differences
- Color handling — sRGB conversion, ICC profiles, bit depth, CMYK, and HDR
- Platform support — supported operating systems, CPU architectures, and comparison with sharp
- WebAssembly backend — using and building the WebAssembly worker backend
- Benchmark — throughput against sharp and
@napi-rs/image, and how to run it - Future work — planned improvements
Development
Requires Rust (version pinned in rust-toolchain.toml), Node.js 24, and pnpm (npm install --global pnpm).
pnpm install
pnpm build # or `pnpm build:release` for release builds
pnpm test # Rust unit tests and end-to-end tests (builds first)
pnpm test:release # end-to-end tests with a release build
pnpm lint # clippy and oxlint
pnpm quality # clippy, rustfmt, oxlint, oxfmt, and TypeScript typechecking
pnpm quality:fix # clippy's and oxlint's fixes, rustfmt, and oxfmt
# Regenerate TypeScript protocol types after changing request options in crates/core
# (requires `cargo install typeshare-cli --version 1.13.4 --locked`)
pnpm generateSee docs/wasm.md for instructions on building and testing the WebAssembly backend.
