Skip to content

RFC: Use Sharp for image optimization if installedย #27055

@atcastle

Description

@atcastle

What I'm proposing:

  1. Allow the Next.js image optimizer to use Sharp (libvips) for itโ€™s image transformations, if that library is already present on the server (i.e. installed by the user)
  2. If Next is started in production mode (next start), uses the built-in image optimizer, and Sharp is not present on the server, log a console warning suggesting that the user install Sharp.

Why I'm proposing this

Sharp is a lot faster than Squoosh for this use case. This fact has been noticed by the community since Next.js moved from Sharp to Squoosh, and is an ongoing source of complaints. Some users say this is preventing them from using the image component entirely.

We have no reason to believe that Squoosh will be competitive with Sharp for this use case in the near future.

The two reasons Next.js switched to Squoosh are both addressed by this solution:

  1. For a period, Sharp caused major issues when used on a new M1 Macbook. This issue is now resolved. Sharp can be used on M1 Macbooks.
  2. Sharp slowed down initial Next install times substantially, because it is a large dependency and in some (but not most) cases, libvips and/or sharp must be compiled locally, which adds additional build time. Since many users will not use the built-in image optimizer for production image serving, this is an unacceptable cost. Switching to an opt-in model means that the extra install time is only experienced by users who benefit from Sharp.

How I propose to do this

I propose a solution that checks for the availability of Sharp at server startup using something like this:

let sharp
 try {
   sharp = require('sharp')
 } catch (e) {
   // Missing-sharp fallback logic
 }

We would also do a similar check during SSR or SSG, as part of the default loader provided with the image component. The default loader is what integrates with the image optimizer, so If that loader is called during production, and sharp is not installed, we can log a warning message on the server such as the following:

WARNING: For production image optimization with Next.js, the optional 'sharp' package is strongly recommended. Run 'yarn add sharp' or install sharp globally, and Next.js will use it automatically for image optimization.

The Squoosh code will continue to exist in the Next.js codebase, as it is adequate for a development server use case (though even in that context, Sharp will be used if it available).

The Sharp integration code (similar to what was removed in this PR) will be added back into the codebase, to make use of the Sharp library if it is available.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions