I hope this gives you some more ideas...
I had a similar problem and I ended up with a script (partially generated by Claude because I don't want to code logging etc) that builds optimised images.
It uses sharp
as the image optimiser.
On build, the NextJS builder runs and build the application and create the static generated site in out
folder, then the image optimiser kicks in and creates optimised images and puts them in out
folder. The NextJS config has a custom loader which is used by Next to create the paths on the build time.
The repo is here. Please let me know you thoughts on it...
https://github.com/SaadAhmad123/arvo-sample/blob/main/apps/analyzer/scripts/ssg-image-optimizer.js