Fix image optimization in NextJS (standalone build)

If you are reading this article, you probably already have read this long thread: How run next.js with node-sharp for docker. And probably, like me, tried some solutions from there.

Unfortunately this thread is a bit outdated and has some wrong suggestions. I had to dive deeply into the issue and spent few days figuring out how to fix it, including reading NextJS source code and analyzing it's dependency tree.

The root of the problem is that Sharp library is required for image optimization, but it is marked as an optional dependency for NextJS. You can learn more about optional dependencies and how they work, but the fact is that it is not installed by default during dependencies resolution, what is causing issues with image optimization on the server side.

The worst thing is that it just silently fails in NextJS, without any errors/warnings in the application or build log. This is something, that NextJS team should definitely improve, since image optimization is very critical piece of almost every NextJS website or app.

So, here is what I did to fix it.

Adding Sharp to package.json

First we need to install sharp explicitly via npm or your package manager of choice. The resulting package.json should look something like this:

package.json
"next": "^15.3.4",
"sharp": "^0.34.2",

The important part is that it also installs @img/* packages into node_modules. These packages include prebuilt platform-specific binaries for Sharp library to work properly. We will see why this is important in the next section.

Adjusting NextJS config

Second and the last step — adjusting NextJS config. Since we are using standalone build, we need to tell NextJS to include sharp and @img/* packages to the build output, because they are not imported explicitly in the project, and automatic file tracing fails to detect this dependency (one more thing NextJS team could improve).

next.config.{js|ts}
output: "standalone",
outputFileTracingIncludes: {
  "**": ["./node_modules/sharp/**/*", "./node_modules/@img/**/*"],
}

Note: if you are using older Sharp versions, then including @img/* packages might be not needed, since this separation was introduced only in recent versions of Sharp. Check your node_modules, and if you see @img folder there — make sure it's included into output file tracing config. I recommend using recent versions of Sharp, since it manages it's optional dependencies much more efficiently.

That's it. Hopefully this will help you to fix image optimization in your NextJS standalone build.

send feedback