Deploy sharp with Next.js on Netlify

This is specifically if you're using sharp in Next.js API endpoints, which Netlify deploy as functions. It might be relevant even if you're not using Next.js, but I haven't tested this.

Netlify may fail to build, or the build will be successful but the API endpoint will crash/500 when invoked.

I was getting successful builds, but the endpoint would fail, and the Netlify function log would report Error: Cannot find module 'sharp' because it seems Netlify excludes this package for Reasons(TM).

Next.js documentation recommends adding the NEXT_SHARP_PATH environment variable:

Loading...
NEXT_SHARP_PATH=/tmp/node_modules/sharp

But this doesn't affect Netlify functions. Good to have, though.

Another recommendation was to add sharp to external_node_modules in netlify.toml, which explicitly tells Netlify which external modules to include in the bundle:

netlify.toml
Loading...
[functions] external_node_modules = ["sharp"]

Nice thought, but this didn't change anything for me.

What did work for me was using a package alias to give the sharp package a custom name so that it doesn't get filtered out. This ticket1 uses the yarn syntax, but the npm syntax is similar:

Loading...
npm i some-alias@npm:package@version

This allowed the package to be found, but the package build was now failing with the error Module parse failed: Unexpected character '' (1:0). I've lost where I found this solution, but adding this to the webpack config in next.config.js worked for me:

next.config.js
Loading...
config.module.rules.push({ test: /\.node$/, use: "node-loader" });

Adjust the syntax to whatever it is you're doing in your webpack config.

Anyway, this took far longer than I would have liked to resolve, hopefully this saves you some time.


Footnotes

  1. Further down, another user suggested creating a separate plugin that forcibly includes the sharp module. Tried this, didn't work for me.

Published October 23, 2022