vercel/next.js · #101254

[image-optimizer] Add experimental support for @next/safe-image-optimization

bgw · merged Nov 21, 202620 files · 660 + / 36 −
crates/next-api/src/next_server_nft.rs22 + / 0 −
@@ -286,6 +286,7 @@ fn next_owned_ignores(     has_next_support: bool,     is_standalone: bool,     has_native_routes: bool,+    img_opt_safe_mode_enabled: bool, ) -> Vec<RcStr> {     let mut globs = vec![         rcstr!("**/node_modules/react{,-dom,-server-dom-turbopack}/**/*.development.js"),@@ -325,6 +326,17 @@ fn next_owned_ignores(         globs.push(rcstr!("**/next/dist/server/lib/native-route*.js"));     } +    // `image-optimizer/nsio.js` requires this, but it's only used with+    // `experimental.imgOptSafeMode`. Keep the large platform-specific binary out of other builds.+    // The package path itself is also ignored, or the pnpm symlink to it would be copied and left+    // dangling.+    if !img_opt_safe_mode_enabled {+        globs.push(rcstr!("**/node_modules/@next/safe-image-optimization*"));+        globs.push(rcstr!(+            "**/node_modules/@next/safe-image-optimization*/**/*"+        ));+    }+     // only ignore image-optimizer code when     // this is being handled outside of next-server     if has_next_support {@@ -383,6 +395,11 @@ impl ServerNftJsonAsset {                 *self.project.ci_has_next_support().await?,                 is_standalone,                 *has_native_routes(*self.project).await?,+                *self+                    .project+                    .next_config()+                    .img_opt_safe_mode_enabled()+                    .await?,             )             .into_iter()             .map(|g| Glob::new(g, GlobOptions::default()))@@ -494,6 +511,11 @@ impl ServerNftJsonAsset {             has_next_support,             is_standalone,             *has_native_routes(*self.project).await?,+            *self+                .project+                .next_config()+                .img_opt_safe_mode_enabled()+                .await?,         )         .into_iter()         .chain(additional_ignores)
crates/next-core/src/next_config.rs38 + / 0 −
@@ -1256,6 +1256,7 @@ pub struct ExperimentalConfig {     /// route.     strict_route_matching: Option<bool>,     go_routes: Option<bool>,+    img_opt_safe_mode: Option<ImgOptSafeMode>,     /// Experimental Rust React compiler (Turbopack only); requires `reactCompiler`.     turbopack_rust_react_compiler: Option<bool>,     /// Defaults to false in development mode, true in production mode.@@ -1309,6 +1310,33 @@ pub struct LightningCssFeatures {     pub exclude: Option<Vec<RcStr>>, } +/// `experimental.imgOptSafeMode`. `assignDefaultsAndValidate` normalizes this to the object form+/// with both fields set, but the boolean form is accepted too.+#[derive(Clone, Debug, PartialEq, Deserialize, NonLocalValue, OperationValue, Encode, Decode)]+#[serde(untagged)]+pub enum ImgOptSafeMode {+    Bool(bool),+    #[serde(rename_all = "camelCase")]+    Options {+        next_image: Option<bool>,+        image_response: Option<bool>,+    },+}++impl ImgOptSafeMode {+    /// Whether `@next/safe-image-optimization` is used by any feature. The defaults for omitted+    /// fields match `assignDefaultsAndValidate`.+    fn is_enabled(&self) -> bool {+        match self {+            ImgOptSafeMode::Bool(enabled) => *enabled,+            ImgOptSafeMode::Options {+                next_image,+                image_response,+            } => next_image.unwrap_or(false) || image_response.unwrap_or(false),+        }+    }+}+ #[derive(Clone, Debug, PartialEq, Deserialize, NonLocalValue, OperationValue, Encode, Decode)] #[serde(untagged)] pub enum ServerActionsOrLegacyBool {@@ -1989,6 +2017,16 @@ impl NextConfig {         Vc::cell(self.experimental.go_routes.unwrap_or_default())     } +    #[turbo_tasks::function]+    pub fn img_opt_safe_mode_enabled(&self) -> Vc<bool> {+        Vc::cell(+            self.experimental+                .img_opt_safe_mode+                .as_ref()+                .is_some_and(ImgOptSafeMode::is_enabled),+        )+    }+     #[turbo_tasks::function]     pub fn strict_route_matching(&self) -> Vc<bool> {         Vc::cell(self.experimental.strict_route_matching.unwrap_or_default())
docs/01-app/03-api-reference/04-functions/image-optimizer-transform.mdx29 + / 23 −
@@ -50,7 +50,7 @@ async function imageOptimizerTransform( ): Promise<ImageOptimizerResult> ``` -Validates an upstream image, optimizes it with sharp, and returns the result with caching metadata.+Validates an upstream image, optimizes it with sharp or `@next/safe-image-optimization`, and returns the result with caching metadata.  #### imageUpstream @@ -74,33 +74,38 @@ Validates an upstream image, optimizes it with sharp, and returns the result wit  All fields are optional. -| Field                 | Type              | Default     | Description                                                                                   |-| --------------------- | ----------------- | ----------- | --------------------------------------------------------------------------------------------- |-| `dangerouslyAllowSVG` | `boolean`         | `false`     | Allows SVG sources. When `false`, an SVG source throws an `ImageError`.                       |-| `minimumCacheTTL`     | `number`          | `0`         | The minimum `maxAge` of the result, in seconds.                                               |-| `concurrency`         | `number \| null`  | `undefined` | The sharp thread pool size. When not a number, a default based on `NODE_ENV` is used.         |-| `operationCache`      | `boolean \| null` | `undefined` | Enables or disables the libvips operation cache. When not a boolean, sharp's default is used. |-| `maxInputPixels`      | `number`          | `undefined` | Passed to sharp as `limitInputPixels`. When omitted, sharp's default of `268402689` is used.  |-| `sequentialRead`      | `boolean \| null` | `undefined` | Passed to sharp as `sequentialRead`.                                                          |-| `timeoutInSeconds`    | `number`          | `7`         | Per-image processing timeout.                                                                 |-| `mozjpeg`             | `boolean`         | `true`      | Encodes JPEG output with mozjpeg.                                                             |-| `logger`              | `object`          | `undefined` | A logger with `error(...args)` and `warnOnce(message)`. When omitted, no logging occurs.      |+| Field                   | Type              | Default     | Description                                                                                                                                                                                                 |+| ----------------------- | ----------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `dangerouslyAllowSVG`   | `boolean`         | `false`     | Allows SVG sources. When `false`, an SVG source throws an `ImageError`.                                                                                                                                     |+| `minimumCacheTTL`       | `number`          | `0`         | The minimum `maxAge` of the result, in seconds.                                                                                                                                                             |+| `concurrency`           | `number \| null`  | `undefined` | With sharp, the number of libvips threads used for each image. With `safeImageOptimization`, the maximum number of images optimized in parallel. The default value is derived from the available CPU cores. |+| `operationCache`        | `boolean \| null` | `undefined` | Enables or disables the libvips operation cache. When not a boolean, sharp's default is used. Only used by sharp.                                                                                           |+| `maxInputPixels`        | `number`          | `undefined` | The maximum number of pixels in a source image. When omitted, sharp's default of `268402689` is used.                                                                                                       |+| `sequentialRead`        | `boolean \| null` | `undefined` | Passed to sharp as [`sequentialRead`]. Only used by sharp.                                                                                                                                                  |+| `timeoutInSeconds`      | `number`          | `7`         | Per-image processing timeout.                                                                                                                                                                               |+| `mozjpeg`               | `boolean`         | `true`      | Encodes JPEG output with mozjpeg. Much slower, but produces smaller files.                                                                                                                                  |+| `safeImageOptimization` | `boolean`         | `false`     | Optimizes with `@next/safe-image-optimization` instead of sharp.                                                                                                                                            |+| `logger`                | `object`          | `undefined` | A logger with `error(...args)` and `warnOnce(message)`. When omitted, no logging occurs.                                                                                                                    | -These correspond to the [`images`](/docs/app/api-reference/config/next-config-js/images) and `experimental.imgOpt*` options in `next.config.js`, but the defaults are not the same. For example, Next.js defaults `images.minimumCacheTTL` to `14400`.+[`sequentialRead`]: https://sharp.pixelplumbing.com/api-constructor/#new++These correspond to the [`images`](/docs/app/api-reference/config/next-config-js/images) and `experimental.imgOpt*` options in `next.config.js`, but the defaults are not the same. For example, Next.js defaults `images.minimumCacheTTL` to `14400`. `safeImageOptimization` corresponds to `experimental.imgOptSafeMode.nextImage`.++When `safeImageOptimization` is `true`, only WebP, PNG, JPEG, and GIF output are supported. Requesting another output type returns the upstream image with `error` set. `operationCache` and `sequentialRead` are ignored.  #### Returns  `Promise<ImageOptimizerResult>` with the following fields: -| Field          | Type      | Description                                                                               |-| -------------- | --------- | ----------------------------------------------------------------------------------------- |-| `buffer`       | `Buffer`  | The optimized image, or the upstream image when optimization is skipped or failed.        |-| `contentType`  | `string`  | The MIME type of `buffer`.                                                                |-| `maxAge`       | `number`  | The cache lifetime in seconds.                                                            |-| `etag`         | `string`  | The ETag for the returned buffer.                                                         |-| `upstreamEtag` | `string`  | The ETag of the upstream image.                                                           |-| `optimized`    | `boolean` | `true` when `buffer` was produced by sharp, `false` when the upstream image was returned. |-| `error`        | `unknown` | Present only when optimization failed and the upstream image was returned instead.        |+| Field          | Type      | Description                                                                         |+| -------------- | --------- | ----------------------------------------------------------------------------------- |+| `buffer`       | `Buffer`  | The optimized image, or the upstream image when optimization is skipped or failed.  |+| `contentType`  | `string`  | The MIME type of `buffer`.                                                          |+| `maxAge`       | `number`  | The cache lifetime in seconds.                                                      |+| `etag`         | `string`  | The ETag for the returned buffer.                                                   |+| `upstreamEtag` | `string`  | The ETag of the upstream image.                                                     |+| `optimized`    | `boolean` | `true` when `buffer` was transformed, `false` when the upstream image was returned. |+| `error`        | `unknown` | Present only when optimization failed and the upstream image was returned instead.  |  The function runs the following steps in order: @@ -110,7 +115,7 @@ The function runs the following steps in order: 4. Returns animated WebP, PNG, and GIF sources unoptimized, and calls `logger.warnOnce`. 5. Returns SVG, ICO, ICNS, BMP, JXL, and HEIC sources unmodified. 6. Selects the output type: `paramsResult.mimeType` when non-empty, `image/jpeg` for WebP or AVIF sources when no type is requested, otherwise the detected source type.-7. Resizes and re-encodes the image with sharp using the sharp-related `opts` values. The output is auto-rotated according to the EXIF orientation of the source image.+7. Resizes and re-encodes the image. The output is auto-rotated according to the EXIF orientation of the source image. 8. On failure, returns the upstream buffer and content type with `maxAge` set to `opts.minimumCacheTTL` and the caught value on `result.error`. The failure does not throw.  ### getMaxAge@@ -157,6 +162,7 @@ The error type thrown by `imageOptimizerTransform` for invalid input. `statusCod ## Good to know  - `sharp` is required and is loaded lazily on the first call to `getSharp` or the first image that `imageOptimizerTransform` optimizes. The same instance is reused afterwards.+- `sharp` is not used if `safeImageOptimization` is enabled. - The module intentionally imports very little so it loads quickly in a separate process, such as a worker or child process. Its file location and exports are a stable public contract. - The `contentType` field of `imageUpstream` is not used for detection. The content type is detected from the first bytes of the buffer. - Optimization failures do not throw. `imageOptimizerTransform` returns the upstream buffer with `error` set on the result.
docs/01-app/03-api-reference/05-config/01-next-config-js/serverExternalPackages.mdx1 + / 0 −
@@ -29,6 +29,7 @@ Next.js includes a [short list of popular packages](https://github.com/vercel/ne - `@libsql/client` - `@mikro-orm/core` - `@mikro-orm/knex`+- `@next/safe-image-optimization` - `@node-rs/argon2` - `@node-rs/bcrypt` - `@prisma/client`
docs/02-pages/04-api-reference/04-config/01-next-config-js/serverExternalPackages.mdx1 + / 0 −
@@ -29,6 +29,7 @@ Next.js includes a [short list of popular packages](https://github.com/vercel/ne - `@libsql/client` - `@mikro-orm/core` - `@mikro-orm/knex`+- `@next/safe-image-optimization` - `@node-rs/argon2` - `@node-rs/bcrypt` - `@prisma/client`
packages/next/package.json1 + / 0 −
@@ -104,6 +104,7 @@   },   "dependencies": {     "@next/env": "workspace:*",+    "@next/safe-image-optimization": "0.0.2",     "@swc/helpers": "0.5.24",     "baseline-browser-mapping": "^2.9.19",     "caniuse-lite": "^1.0.30001579",
packages/next/src/build/collect-build-traces.ts13 + / 0 −
@@ -297,6 +297,19 @@ export async function collectBuildTraces({         ...(ciEnvironment.hasNextSupport           ? ['**/node_modules/sharp/**/*', '**/@img/sharp-libvips*/**/*']           : []),+        // `image-optimizer/nsio.js` requires this, but next-server only uses it+        // with `experimental.imgOptSafeMode`. Keep the large platform-specific+        // binary out of the server trace otherwise. Route traces aren't+        // affected, since routes can call `imageOptimizerTransform()` directly.+        // The package path itself is also ignored, or the pnpm symlink to it+        // would be copied and left dangling.+        ...(config.experimental.imgOptSafeMode.nextImage ||+        config.experimental.imgOptSafeMode.imageResponse+          ? []+          : [+              '**/node_modules/@next/safe-image-optimization*',+              '**/node_modules/@next/safe-image-optimization*/**/*',+            ]),       ].filter(nonNullable)       const serverIgnoreFn = makeIgnoreFn(root, serverIgnores) 
packages/next/src/build/webpack/loaders/next-image-loader/blur.ts2 + / 0 −
@@ -1,5 +1,6 @@ import isAnimated from 'next/dist/compiled/is-animated' import { optimizeImage } from '../../../../server/image-optimizer/sharp'+import { DEFAULT_IMG_OPT_TIMEOUT_IN_SECONDS } from '../../../../shared/lib/image-optimizer-constants'  const BLUR_IMG_SIZE = 8 const BLUR_QUALITY = 70@@ -72,6 +73,7 @@ export async function getBlurImage(           height: blurHeight,           contentType: `image/${extension}`,           quality: BLUR_QUALITY,+          timeoutInSeconds: DEFAULT_IMG_OPT_TIMEOUT_IN_SECONDS,         })       )       const blurDataURLSpan = tracing('image-base64-tostring')
packages/next/src/lib/server-external-packages.jsonc2 + / 0 −
@@ -11,6 +11,8 @@   "@libsql/client",   "@mikro-orm/core",   "@mikro-orm/knex",+  // Spawns a platform-specific worker binary located relative to its package+  "@next/safe-image-optimization",   "@node-rs/argon2",   "@node-rs/bcrypt",   "@prisma/client",
packages/next/src/server/config-schema.ts9 + / 0 −
@@ -296,6 +296,15 @@ export const experimentalSchema = {   imgOptMaxInputPixels: z.number().int().optional(),   imgOptSequentialRead: z.boolean().optional().nullable(),   imgOptMozjpeg: z.boolean().optional(),+  imgOptSafeMode: z+    .union([+      z.boolean(),+      z.strictObject({+        nextImage: z.boolean().optional(),+        imageResponse: z.boolean().optional(),+      }),+    ])+    .optional(),   isrFlushToDisk: z.boolean().optional(),   largePageDataBytes: z.number().optional(),   linkNoTouchStart: z.boolean().optional(),
packages/next/src/server/config-shared.ts66 + / 1 −
@@ -17,6 +17,7 @@ import { deepFreeze } from '../shared/lib/deep-freeze' import type { FallbackRouteParam } from '../build/static-paths/types' import type { MemoryEvictionMode, TurbopackGcOptions } from '../build/swc/types' import type { CacheLife } from './use-cache/cache-life'+import { DEFAULT_IMG_OPT_TIMEOUT_IN_SECONDS } from '../shared/lib/image-optimizer-constants'  /**  * The `cacheLife` profiles after config normalization. `config.ts` always@@ -38,6 +39,16 @@ export type PrefetchInliningConfig =   | false   | { maxSize: number; maxBundleSize: number } +/**+ * Resolved form of the `imgOptSafeMode` config after+ * normalization in config.ts. Booleans and partial objects are converted to+ * this shape.+ */+export interface ImgOptSafeModeConfig {+  nextImage: boolean+  imageResponse: boolean+}+ export type NextConfigComplete = Required<   Omit<     NextConfig,@@ -85,6 +96,9 @@ export type NextConfigComplete = Required<       // Normalized by config.ts: `false` becomes `undefined` (GC off),       // `true`/unset becomes `{}` (GC on with default timings)       turbopackGcOptions: TurbopackGcOptions | undefined+      // Normalized by config.ts: booleans and partial objects become resolved+      // objects+      imgOptSafeMode: ImgOptSafeModeConfig     }     // The root directory of the distDir. In development mode, this is the parent directory of `distDir`     // since development builds use `{distDir}/dev`. This is used to ensure that the bundler doesn't@@ -659,12 +673,60 @@ export interface ExperimentalConfig {   extensionAlias?: Record<string, any>   allowedRevalidateHeaderKeys?: string[]   fetchCacheKeyPrefix?: string+  /**+   * With `sharp`, this is the number of libvips threads used to process each+   * image. The number of images processed in parallel is bounded by+   * `UV_THREADPOOL_SIZE`. With `imgOptSafeMode`, this is the size of the+   * worker process pool, which is the maximum number of images optimized in+   * parallel.+   *+   * `null` selects a default. With `sharp`, this is a fraction of the+   * available CPUs, depending on `NODE_ENV`. With+   * `imgOptSafeMode`, this is the number of available CPUs.+   */   imgOptConcurrency?: number | null   imgOptOperationCache?: boolean | null   imgOptTimeoutInSeconds?: number   imgOptMaxInputPixels?: number   imgOptSequentialRead?: boolean | null   imgOptMozjpeg?: boolean+  /**+   * Uses `@next/safe-image-optimization` instead of `sharp`. This utilizes+   * memory-safe image decoders written in Rust combined with OS-level+   * sandboxing on Linux. It does not support some uncommon image formats, and+   * it may sacrifice some performance.+   *+   * This will have no effect in production if your hosting platform (e.g.+   * Vercel) provides image optimization as a service by overriding the+   * `_next/image` route.+   *+   * This also has no effect if a custom loader is configured with+   * `images.loader: 'custom'` and [`images.loaderFile`], as the built-in image+   * optimizer is not used.+   *+   * `true` enables it everywhere. An object enables it individually for+   * `next/image` (`nextImage`) and `ImageResponse` (`imageResponse`). Omitted+   * keys default to `false`.+   *+   * Currently, only `nextImage` is implemented. `imageResponse` has no effect+   * yet.+   *+   * Compared to `sharp`, for `next/image`:+   * - Output formats: Only WebP, PNG, JPEG, and GIF output are supported.+   *   Unsupported values in `images.formats` (i.e. AVIF) generate a warning and+   *   are ignored.+   * - `imgOptSequentialRead` and `imgOptOperationCache` are ignored.+   *+   * [`images.loaderFile`]: https://nextjs.org/docs/app/api-reference/components/image#loaderfile+   *+   * @default false+   */+  imgOptSafeMode?:+    | boolean+    | {+        nextImage?: boolean+        imageResponse?: boolean+      }   optimisticClientCache?: boolean   /**    * @deprecated use config.expireTime instead@@ -2522,10 +2584,11 @@ export const defaultConfig = Object.freeze({     memoryBasedWorkersCount: false,     imgOptConcurrency: null,     imgOptOperationCache: null,-    imgOptTimeoutInSeconds: 7,+    imgOptTimeoutInSeconds: DEFAULT_IMG_OPT_TIMEOUT_IN_SECONDS,     imgOptMaxInputPixels: 268_402_689, // https://sharp.pixelplumbing.com/api-constructor#:~:text=%5Boptions.limitInputPixels%5D     imgOptSequentialRead: null,     imgOptMozjpeg: true,+    imgOptSafeMode: false,     isrFlushToDisk: true,     workerThreads: false,     proxyTimeout: undefined,@@ -2716,6 +2779,7 @@ export interface NextConfigRuntime {     | 'imgOptSequentialRead'     | 'imgOptTimeoutInSeconds'     | 'imgOptMozjpeg'+    | 'imgOptSafeMode'     | 'proxyClientMaxBodySize'     | 'proxyTimeout'     | 'testProxy'@@ -2790,6 +2854,7 @@ export function getNextConfigRuntime(     imgOptSequentialRead: ex.imgOptSequentialRead,     imgOptTimeoutInSeconds: ex.imgOptTimeoutInSeconds,     imgOptMozjpeg: ex.imgOptMozjpeg,+    imgOptSafeMode: ex.imgOptSafeMode,     proxyClientMaxBodySize: ex.proxyClientMaxBodySize,     proxyTimeout: ex.proxyTimeout,     testProxy: ex.testProxy,
packages/next/src/server/config.ts46 + / 0 −
@@ -66,6 +66,7 @@ import { hrtimeBigIntDurationToString } from '../build/duration-to-string' export { normalizeConfig } from './config-shared' import { verifyDistDir } from '../lib/dist-dir' import { isStableBuild } from '../shared/lib/errors/canary-only-config-error'+import { NSIO_OUTPUT_MIME_TYPES } from '../shared/lib/image-optimizer-constants' export type { DomainLocale, NextConfig } from './config-shared'  const REACT_18_DEPRECATION_WARNING =@@ -950,6 +951,51 @@ function assignDefaultsAndValidate(     }   } +  // Normalize imgOptSafeMode: boolean | { nextImage?,+  // imageResponse? } into a resolved object. `true` enables every feature, and+  // omitted keys in the object form are disabled.+  const safeImgOpt = result.experimental.imgOptSafeMode+  const resolvedSafeImgOpt =+    typeof safeImgOpt === 'object'+      ? {+          nextImage: safeImgOpt.nextImage ?? false,+          imageResponse: safeImgOpt.imageResponse ?? false,+        }+      : { nextImage: !!safeImgOpt, imageResponse: !!safeImgOpt }+  ;(result as NextConfigComplete).experimental.imgOptSafeMode =+    resolvedSafeImgOpt++  // `ImageOptimizerCache.validateParams` filters out unsupported formats. Nsio+  // does not support all the output formats that Sharp does (notably AVIF).+  // Warn about it here so that the warning is shown at startup.+  //+  // Don't filter them out of NextConfigComplete. If there's an optimization+  // service used by the adapter (e.g. Vercel Image Optimization), we may+  // actually be able to handle this value when deployed.+  const userImageFormats = userConfig.images?.formats+  if (+    userImageFormats &&+    resolvedSafeImgOpt.nextImage &&+    // Otherwise the image optimizer isn't used+    result.images?.loader === 'default' &&+    !result.images.unoptimized &&+    !silent+  ) {+    const unsupportedFormats = userImageFormats.filter(+      (format) => !NSIO_OUTPUT_MIME_TYPES.includes(format)+    )+    if (unsupportedFormats.length > 0) {+      // TODO: when turning on `imgOptSafeMode` by default, give+      // users an easy way to disable this warning if they're using an external+      // image optimization provider that supports the output format, and then+      // document that in the warning. E.g. Vercel does this at the proxy layer+      // for `_next/image`, so we can't know that here.+      Log.warnOnce(+        `Some "images.formats" are ignored when using "experimental.imgOptSafeMode": ${unsupportedFormats.join(', ')}`+      )+    }+  }+   warnCustomizedOption(     result,     'experimental.esmExternals',
packages/next/src/server/image-optimizer.ts20 + / 2 −
@@ -61,6 +61,7 @@ import { getMaxAge } from './image-optimizer/get-max-age' import { getPreviouslyCachedImageOrNull } from './image-optimizer/get-previously-cached-image-or-null' import { getImageSize } from './image-optimizer/get-image-size' import { ImageError } from './image-optimizer/image-error'+import { NSIO_OUTPUT_MIME_TYPES } from '../shared/lib/image-optimizer-constants'  // `next-server.ts` destructures `ImageError` from this module to check // `instanceof` on errors thrown by the transform.@@ -178,6 +179,10 @@ function validateUrlParam( }  function getSupportedMimeType(options: string[], accept = ''): string {+  // With no preferences, `mediaType()` returns the client's preferred type.+  if (options.length === 0) {+    return ''+  }   const mimeType = mediaType(accept, options)   return accept.includes(mimeType) ? mimeType : '' }@@ -335,7 +340,18 @@ export class ImageOptimizerCache {       }     } -    const mimeType = getSupportedMimeType(formats || [], req.headers['accept'])+    let supportedFormats: string[] = formats || []+    if (nextConfig.experimental?.imgOptSafeMode?.nextImage) {+      // `config.ts` warns about the formats that are filtered out+      supportedFormats = supportedFormats.filter((format) =>+        NSIO_OUTPUT_MIME_TYPES.includes(format)+      )+    }++    const mimeType = getSupportedMimeType(+      supportedFormats,+      req.headers['accept']+    )     const { href, isAbsolute } = urlResult     const isStatic =       href.startsWith(`${nextConfig.basePath || ''}/_next/static/media`) ||@@ -1118,7 +1134,8 @@ type ImageOptimizerNextConfig = {     | 'imgOptSequentialRead'     | 'imgOptTimeoutInSeconds'     | 'imgOptMozjpeg'-  >+  > &+    Partial<Pick<NextConfigComplete['experimental'], 'imgOptSafeMode'>>   images: Pick<     NextConfigComplete['images'],     'dangerouslyAllowSVG' | 'minimumCacheTTL'@@ -1149,6 +1166,7 @@ export function getImageOptimizerTransformOptions(     sequentialRead: nextConfig.experimental.imgOptSequentialRead,     timeoutInSeconds: nextConfig.experimental.imgOptTimeoutInSeconds,     mozjpeg: nextConfig.experimental.imgOptMozjpeg,+    safeImageOptimization: nextConfig.experimental.imgOptSafeMode?.nextImage,   } } 
packages/next/src/server/image-optimizer/nsio.tsadded105 + / 0 −
@@ -0,0 +1,105 @@+// nsio (`@next/safe-image-optimization`) is an alternative to sharp, enabled by+// `experimental.imgOptSafeMode`.+//+// This module is imported by `transform.ts`, which runs in a child process, so+// keep its imports minimal. nsio itself is only required when it's used.+import type { Pool } from '@next/safe-image-optimization'+import { GIF, JPEG, PNG, WEBP } from './image-type'+import {+  NSIO_INPUT_FORMATS,+  NSIO_OUTPUT_MIME_TYPES,+} from '../../shared/lib/image-optimizer-constants'++let _pool: Pool | undefined++function getPool(+  concurrency: number | null | undefined,+  logger: { warnOnce(message: string): void } | undefined+): Pool {+  if (!_pool) {+    try {+      const { Pool } =+        require('@next/safe-image-optimization') as typeof import('@next/safe-image-optimization')+      // `Pool` rejects `0`, but sharp treats it as "use the default", so match+      // that+      _pool = new Pool({ concurrency: concurrency || undefined })+    } catch (error) {+      // The caller falls back to the unoptimized image without logging, so+      // warn here, or a misconfiguration (e.g. no worker binary for this+      // platform) would go unnoticed+      logger?.warnOnce(+        `Failed to initialize "@next/safe-image-optimization" for "experimental.imgOptSafeMode", images will not be optimized: ${error}`+      )+      throw error+    }+  }+  return _pool+}++/**+ * The `@next/safe-image-optimization` equivalent of `optimizeImage()`.+ * Supported options are slightly different.+ *+ * Note: Unlike sharp, nsio has no operation cache, so every request decodes and+ * encodes again. This is likely fine, as Next.js has a disk cache that's+ * checked before calling either sharp or nsio.+ */+export async function nsioOptimizeImage({+  buffer,+  contentType,+  quality,+  width,+  concurrency,+  maxInputPixels,+  timeoutInSeconds,+  mozjpeg = true,+  logger,+}: {+  buffer: Buffer+  contentType: string+  quality: number+  width: number+  concurrency?: number | null+  maxInputPixels?: number+  timeoutInSeconds: number+  mozjpeg?: boolean+  logger?: { warnOnce(message: string): void }+}): Promise<Buffer> {+  if (!NSIO_OUTPUT_MIME_TYPES.includes(contentType)) {+    // The caller catches this error and falls back to the source (unoptimized)+    // image+    throw new Error(+      `Unsupported output content type for nsio image optimization: ${contentType}`+    )+  }++  const pipeline = getPool(concurrency, logger)+    .prepare(buffer)+    .allowInputFormats(NSIO_INPUT_FORMATS)+    .timeoutMs(timeoutInSeconds * 1000)+    .autoOrient()+    .resize(width, null, { withoutEnlargement: true })++  if (maxInputPixels !== undefined) {+    pipeline.limitInputPixels(maxInputPixels)+  }++  if (contentType === WEBP) {+    pipeline.webp({ quality })+  } else if (contentType === PNG) {+    // Unlike sharp, there's no palette quantization, so `quality` doesn't+    // apply to PNGs.+    pipeline.png()+  } else if (contentType === JPEG) {+    // Like sharp, mozjpeg output is progressive, and baseline otherwise.+    pipeline.jpeg({ quality, mozjpeg })+  } else if (contentType === GIF) {+    pipeline.gif()+  } else {+    throw new Error(+      'unreachable: contentType must be in NSIO_OUTPUT_MIME_TYPES'+    )+  }++  return pipeline.toBuffer()+}
packages/next/src/server/image-optimizer/sharp.ts3 + / 3 −
@@ -23,7 +23,7 @@ export function getSharp(         'VipsForeignLoadJpeg',         'VipsForeignLoadNsgif',         'VipsForeignLoadPng',-        'VipsForeignLoadSvg',+        'VipsForeignLoadSvg', // used by ImageResponse         'VipsForeignLoadTiff',         'VipsForeignLoadWebp',       ],@@ -73,7 +73,7 @@ export async function optimizeImage({   operationCache?: boolean | null | undefined   maxInputPixels?: number   sequentialRead?: boolean | null-  timeoutInSeconds?: number+  timeoutInSeconds: number   mozjpeg?: boolean }): Promise<Buffer> {   const sharp = getSharp(concurrency, operationCache)@@ -82,7 +82,7 @@ export async function optimizeImage({     sequentialRead: sequentialRead ?? undefined,   })     .timeout({-      seconds: timeoutInSeconds ?? 7,+      seconds: timeoutInSeconds,     })     .rotate() 
packages/next/src/server/image-optimizer/transform.ts23 + / 6 −
@@ -23,6 +23,8 @@ import { getImageEtag } from './extract-etag' import { getMaxAge } from './get-max-age' import { ImageError } from './image-error' import { getSharp, optimizeImage } from './sharp'+import { nsioOptimizeImage } from './nsio'+import { DEFAULT_IMG_OPT_TIMEOUT_IN_SECONDS } from '../../shared/lib/image-optimizer-constants'  export { ImageError } export { getMaxAge }@@ -58,7 +60,11 @@ export interface ImageOptimizerTransformOptions {   dangerouslyAllowSVG?: boolean   /** The minimum `maxAge` of the result, in seconds. Defaults to `0`. */   minimumCacheTTL?: number-  /** The sharp thread pool size. */+  /**+   * With sharp, the number of libvips threads used for each image. With+   * `safeImageOptimization`, the maximum number of images optimized in+   * parallel.+   */   concurrency?: number | null   /** Enables or disables the libvips operation cache. */   operationCache?: boolean | null@@ -70,6 +76,11 @@ export interface ImageOptimizerTransformOptions {   timeoutInSeconds?: number   /** Encodes JPEG output with mozjpeg. Defaults to `true`. */   mozjpeg?: boolean+  /**+   * Optimizes with `@next/safe-image-optimization` (nsio) instead of sharp.+   * Defaults to `false`.+   */+  safeImageOptimization?: boolean   logger?: ImageOptimizerTransformLogger } @@ -80,9 +91,8 @@ export interface ImageOptimizerResult {   etag: string   upstreamEtag: string   /**-   * `true` when `buffer` was produced by sharp. `false` when the upstream-   * image was passed through (animated, a bypassed type, or optimization-   * failed).+   * `true` when `buffer` was transformed. `false` when the upstream image was+   * passed through (animated, a bypassed type, or optimization failed).    */   optimized: boolean   error?: unknown@@ -96,6 +106,9 @@ export async function imageOptimizerTransform(   const { href, quality, width, mimeType } = paramsResult   const { buffer: upstreamBuffer, etag: upstreamEtag } = imageUpstream   const { dangerouslyAllowSVG = false, minimumCacheTTL = 0 } = opts+  // `??` instead of a destructuring default, so that `null` is also replaced+  const timeoutInSeconds =+    opts.timeoutInSeconds ?? DEFAULT_IMG_OPT_TIMEOUT_IN_SECONDS   const maxAge = Math.max(     minimumCacheTTL,     getMaxAge(imageUpstream.cacheControl)@@ -160,13 +173,17 @@ export async function imageOptimizerTransform(   }    try {-    const optimizedBuffer = await optimizeImage({+    const optimizeOpts = {       ...opts,       buffer: upstreamBuffer,       contentType,       quality,       width,-    })+      timeoutInSeconds,+    }+    const optimizedBuffer = opts.safeImageOptimization+      ? await nsioOptimizeImage(optimizeOpts)+      : await optimizeImage(optimizeOpts)     return {       buffer: optimizedBuffer,       contentType,
packages/next/src/shared/lib/image-optimizer-constants.tsadded34 + / 0 −
@@ -0,0 +1,34 @@+// Keep this outside server/image-optimizer/: standalone tracing excludes that+// directory when the hosting platform handles image optimization, but+// config.ts and config-shared.ts always need these constants.+// This also runs in image optimizer child processes, so keep it free of imports.++/** The default for `experimental.imgOptTimeoutInSeconds`. */+export const DEFAULT_IMG_OPT_TIMEOUT_IN_SECONDS = 7++/** The content types that nsio can encode. */+export const NSIO_OUTPUT_MIME_TYPES: readonly string[] = [+  'image/gif',+  'image/jpeg',+  'image/png',+  'image/webp',+]++/**+ * The input formats that nsio allows. These are the same formats that+ * `getSharp()` allows, minus HEIC/HEIF, which is blocked by+ * `imageOptimizerTransform`, and minus SVG, which is never optimized, even+ * with `dangerouslyAllowSVG` (it's passed through instead).+ *+ * nsio throws if it sees an input image that is not allowlisted, which+ * protects against type confusion bugs.+ * e.g. https://github.com/vercel/next.js/security/advisories/GHSA-7qx7-33qx-rqx2+ */+export const NSIO_INPUT_FORMATS = [+  'avif',+  'gif',+  'jpeg',+  'png',+  'tiff',+  'webp',+] as const
pnpm-lock.yaml96 + / 0 −
@@ -1286,6 +1286,9 @@ importers:       '@next/env':         specifier: workspace:*         version: link:../next-env+      '@next/safe-image-optimization':+        specifier: 0.0.2+        version: 0.0.2       '@swc/helpers':         specifier: 0.5.24         version: 0.5.24@@ -5390,6 +5393,60 @@ packages:   '@next/rspack-core@1.0.3':     resolution: {integrity: sha512-4EDUKhRIuljVhTDjy8DqGvTrWrZIFUHffdAThSB3OAEyCPm+pgM3JedSodm00Od5ox0PpsZ0nWY2sbwsJofg2A==} +  '@next/safe-image-optimization-darwin-arm64@0.0.2':+    resolution: {integrity: sha512-9LXsPNrc6wG3P8/u2aOKVTd1Pk71j8oXmORp5v36xZlcLnilqdFtvgd5Hu3Fu7ftqteezqql3EBsLIrS5NRNXQ==}+    cpu: [arm64]+    os: [darwin]++  '@next/safe-image-optimization-darwin-x64@0.0.2':+    resolution: {integrity: sha512-l/FMhx9fCK6i8zU5f3sQu+F36CyzehcvFei+XWsp/fHa+0uZkUXZll9Xk/j4KQODcvbjDCzCZdJULZP8txar6Q==}+    cpu: [x64]+    os: [darwin]++  '@next/safe-image-optimization-linux-arm64-gnu@0.0.2':+    resolution: {integrity: sha512-ikhfpxJ4qx6ZOWAv5xpSWten4Cmzh7EcXh1rNyRJ5s7/41TX7G2rUSqsgOBhRiFKVlaO2XNxNpoXa1JokHQ2aA==}+    cpu: [arm64]+    os: [linux]+    libc: [glibc]++  '@next/safe-image-optimization-linux-arm64-musl@0.0.2':+    resolution: {integrity: sha512-QDkFYYVtdlf1AEg56f16xuaxwruyyvPicFMkjQKgn27rTu+Bios554VqnW1zsrMRUxextZiUL3m5Kc3n1RPZ2g==}+    cpu: [arm64]+    os: [linux]+    libc: [musl]++  '@next/safe-image-optimization-linux-riscv64-gnu@0.0.2':+    resolution: {integrity: sha512-LBMZ2oXDAU7PlqPyI4xdjHF0k5d67J7/StmH4Aj6PMVfDX6oEJ5RoX2dWfxRhpuZlHVIk2ns2hEEDQbBP/I4Fg==}+    cpu: [riscv64]+    os: [linux]+    libc: [glibc]++  '@next/safe-image-optimization-linux-x64-gnu@0.0.2':+    resolution: {integrity: sha512-7t3jBZKZIxJd/4AHH+O61Huc8fGVlq4e4IgkJHR7zSkUltm1w+/i759WLNcEtDZ+nKslGDrVH2ZXGnrxC9nSMw==}+    cpu: [x64]+    os: [linux]+    libc: [glibc]++  '@next/safe-image-optimization-linux-x64-musl@0.0.2':+    resolution: {integrity: sha512-RAONgGlj8cOu9phpyvbSDnYUZuHfMwDKrxbJ2ioAken2+FkIKrER9Drsf7jp3cWWhL+dXjfrPdfWjIFJXnvJ3g==}+    cpu: [x64]+    os: [linux]+    libc: [musl]++  '@next/safe-image-optimization-win32-arm64-msvc@0.0.2':+    resolution: {integrity: sha512-K61PpzH2CE6KA2SRPpSjEdC49s4YWKiHmKBqfyFaSJgC0KkBZsc3ewiEyBg475wNtLiqgWyp3TCWPrw3HZ7MeQ==}+    cpu: [arm64]+    os: [win32]++  '@next/safe-image-optimization-win32-x64-msvc@0.0.2':+    resolution: {integrity: sha512-7JW5zPojaMCmBK3ZpmleQMiqvp3hcfprZ4cc5Jy2rAdsqAwapm23yBUO7Le6tuwqkPhMyN/QrYEV3VkOUGQu/Q==}+    cpu: [x64]+    os: [win32]++  '@next/safe-image-optimization@0.0.2':+    resolution: {integrity: sha512-8Lxme1e+YYjztMchFlJO7NOw5gybzIDiRmzjn1McLfNx4nxfmosZX5jV373QnVXCWPiQUPA+19CNbXTbsEeWeA==}+    engines: {node: '>= 20.9.0'}+   '@next/swc-darwin-arm64@16.4.0-canary.31':     resolution: {integrity: sha512-vWxGWVjr8TEO7sqESJyp1Wr+Xd6XuQ0YkN6UmxwNKlYOx4Y6DnVpsJv0GKyGMQayITZ75tLHq6IeMCPQmnUITA==}     engines: {node: '>= 10'}@@ -22384,6 +22441,45 @@ snapshots:       - '@module-federation/runtime-tools'       - '@swc/helpers' +  '@next/safe-image-optimization-darwin-arm64@0.0.2':+    optional: true++  '@next/safe-image-optimization-darwin-x64@0.0.2':+    optional: true++  '@next/safe-image-optimization-linux-arm64-gnu@0.0.2':+    optional: true++  '@next/safe-image-optimization-linux-arm64-musl@0.0.2':+    optional: true++  '@next/safe-image-optimization-linux-riscv64-gnu@0.0.2':+    optional: true++  '@next/safe-image-optimization-linux-x64-gnu@0.0.2':+    optional: true++  '@next/safe-image-optimization-linux-x64-musl@0.0.2':+    optional: true++  '@next/safe-image-optimization-win32-arm64-msvc@0.0.2':+    optional: true++  '@next/safe-image-optimization-win32-x64-msvc@0.0.2':+    optional: true++  '@next/safe-image-optimization@0.0.2':+    optionalDependencies:+      '@next/safe-image-optimization-darwin-arm64': 0.0.2+      '@next/safe-image-optimization-darwin-x64': 0.0.2+      '@next/safe-image-optimization-linux-arm64-gnu': 0.0.2+      '@next/safe-image-optimization-linux-arm64-musl': 0.0.2+      '@next/safe-image-optimization-linux-riscv64-gnu': 0.0.2+      '@next/safe-image-optimization-linux-x64-gnu': 0.0.2+      '@next/safe-image-optimization-linux-x64-musl': 0.0.2+      '@next/safe-image-optimization-win32-arm64-msvc': 0.0.2+      '@next/safe-image-optimization-win32-x64-msvc': 0.0.2+   '@next/swc-darwin-arm64@16.4.0-canary.31':     optional: true 
test/e2e/image-optimizer/img-opt-safe-mode.test.tsadded40 + / 0 −
@@ -0,0 +1,40 @@+import { join } from 'path'+import { nextTestSetup } from 'e2e-utils'+import { expectWidth, setupTests } from './util'++// Deployments use the Vercel image CDN instead of the local image pipeline.+// @force-gate !deploy+describe('with experimental.imgOptSafeMode', () => {+  // AVIF output isn't supported, so the shared AVIF tests don't apply.+  setupTests({+    nextConfigImages: { formats: ['image/webp'] },+    nextConfigExperimental: { imgOptSafeMode: true },+  })++  describe('with only AVIF in images.formats', () => {+    const { next } = nextTestSetup({+      files: join(__dirname, 'app'),+      nextConfig: {+        images: { formats: ['image/avif'] },+        experimental: { imgOptSafeMode: { nextImage: true } },+      },+    })++    it('should ignore avif and keep the source format', async () => {+      const res = await next.fetch('/_next/image?url=/test.png&w=384&q=75', {+        headers: {+          accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',+        },+      })+      expect(res.status).toBe(200)+      expect(res.headers.get('Content-Type')).toBe('image/png')+      expect(res.headers.get('Content-Disposition')).toBe(+        'attachment; filename="test.png"'+      )+      await expectWidth(res, 384)+      expect(next.cliOutput).toContain(+        'Some "images.formats" are ignored when using "experimental.imgOptSafeMode": image/avif'+      )+    })+  })+})
test/unit/image-optimizer/transform.test.ts109 + / 1 −
@@ -151,6 +151,108 @@ describe('imageOptimizerTransform', () => {     }   ) +  describe('with safeImageOptimization', () => {+    const safeOptions: ImageOptimizerTransformOptions = {+      ...transformOptions,+      safeImageOptimization: true,+    }++    it.each([undefined, true, false])(+      'encodes JPEGs with mozjpeg=%s',+      async (mozjpeg) => {+        const result = await transform('test.jpg', 'image/jpeg', {+          ...safeOptions,+          mozjpeg,+        })+        expect(result.error).toBeUndefined()+        expect(result.contentType).toBe('image/jpeg')+        const sharp = getSharp(1, false)+        expect(await sharp(result.buffer).metadata()).toMatchObject({+          format: 'jpeg',+          width: 64,+        })+        // sharp's `isProgressive` is true for any JPEG with multiple scans,+        // which includes nsio's baseline output, so look for the progressive+        // (SOF2) marker instead.+        expect(result.buffer.includes(Buffer.from([0xff, 0xc2]))).toBe(+          mozjpeg ?? true+        )+      }+    )++    it('passes svg input through with dangerouslyAllowSVG', async () => {+      const source = await getImage('test.svg')+      const result = await transform('test.svg', 'image/webp', safeOptions)+      expect(result.error).toBeUndefined()+      expect(result.optimized).toBe(false)+      expect(result.buffer).toEqual(source)+      expect(result.contentType).toBe('image/svg+xml')+    })++    // SVG is only decoded if `detectContentType()` misidentifies it (type+    // confusion), and `imageOptimizerTransform()` passes real SVGs through, so+    // this calls `nsioOptimizeImage()` directly.+    it('rejects svg input', async () => {+      const { nsioOptimizeImage } =+        require('next/dist/server/image-optimizer/nsio') as typeof import('next/dist/server/image-optimizer/nsio')+      await expect(+        nsioOptimizeImage({+          buffer: await getImage('test.svg'),+          contentType: 'image/png',+          quality: 75,+          width: 64,+          timeoutInSeconds: 6,+        })+      ).rejects.toMatchObject({ code: 'ERR_UNSUPPORTED_FORMAT' })+    })++    it.each([+      ['test.png', 'image/webp', 'webp'],+      ['test.jpg', 'image/jpeg', 'jpeg'],+      ['test.avif', 'image/png', 'png'],+      ['test.gif', '', 'gif'],+    ])('transforms %s with mimeType %p', async (filename, mimeType, format) => {+      const result = await transform(filename, mimeType, safeOptions)+      expect(result.error).toBeUndefined()+      expect(result.contentType).toBe(`image/${format}`)+      const sharp = getSharp(1, false)+      expect(await sharp(result.buffer).metadata()).toMatchObject({+        format,+        width: 64,+      })+    })++    it('falls back to the upstream image for avif output', async () => {+      const source = await getImage('test.png')+      const result = await transform('test.png', 'image/avif', safeOptions)+      expect(result.error).toBeDefined()+      expect(result.buffer).toEqual(source)+      expect(result.contentType).toBe('image/png')+    })++    // nsio doesn't support avif output, so this tells nsio and sharp apart.+    it.each([+      [undefined, false],+      [true, true],+      [false, false],+    ])(+      'with safeImageOptimization=%p, uses nsio: %p',+      async (safeImageOptimization, usesNsio) => {+        const result = await transform('test.png', 'image/avif', {+          ...transformOptions,+          safeImageOptimization,+        })+        if (usesNsio) {+          expect(result.error).toBeDefined()+          expect(result.contentType).toBe('image/png')+        } else {+          expect(result.error).toBeUndefined()+          expect(result.contentType).toBe('image/avif')+        }+      }+    )+  })+   it('preserves the source format when no output format is requested', async () => {     const result = await transform('test.png', '')     expect(result.contentType).toBe('image/png')@@ -178,7 +280,13 @@ describe('imageOptimizerTransform', () => {     // An image already encoded with the blur settings round-trips through     // sharp unchanged, so its optimized etag matches its upstream etag.     const encode = (buffer: Buffer) =>-      optimizeImage({ buffer, contentType: 'image/png', quality: 70, width: 8 })+      optimizeImage({+        buffer,+        contentType: 'image/png',+        quality: 70,+        width: 8,+        timeoutInSeconds: 7,+      })     const source = await encode(await encode(await getImage('test.png')))     expect(await encode(source)).toEqual(source)