npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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 disconnects

To 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, or ArrayBuffer only). 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), with withoutEnlargement, withoutReduction, and kernel options.
  • Input restrictions and limits (0 removes a limit):
    • .allowInputFormats(formats) restricts which formats are accepted (detected from the file contents).
    • .animated('reject') rejects animated images with ERR_ANIMATED before 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 an AbortSignal.
  • Errors: Processing errors throw a SafeImageOptimizationError with a stable code property (such as ERR_UNSUPPORTED_FORMAT, ERR_LIMIT_EXCEEDED, or ERR_TIMEOUT). Invalid options throw a TypeError with the code ERR_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

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 generate

See docs/wasm.md for instructions on building and testing the WebAssembly backend.