unjs / ipx

🖼️ High performance, secure and easy-to-use image optimizer.
MIT License
1.54k stars 61 forks source link

Add a possibility to pass a fallback image url to the options #59

Open Takheer opened 2 years ago

Takheer commented 2 years ago

In my project, I need to get images via ipx, and if there is no such image, I would love to get some placeholder that I would have specified in options. So, is there any way to add such a thing, so the initialization would look like

import { createIPX, createIPXMiddleware } from "ipx";

const ipx = createIPX({
  /* other options */
  fallbackUrl: '/path/to/the/image.png'
});
const app = express();
app.use("/image", createIPXMiddleware(ipx));

Or is there already a way I could handle such 404 errors myself?

Takheer commented 2 years ago

For those who could face a similar problem, I solved it by creating a node middleware that looks if there is an attempt to fetch something using the /_ipx route, and if the server doesn't have such an image, it will redirect to the specified placeholder:

import { existsSync } from 'fs';

export default function (req, res, next) {
  if (
    req.url.includes('/_ipx') &&
    !existsSync('static/img/path.png') // you can parse the req.url to get the path of the image of interest
  ) {
    res.redirect('path/to/the/placeholder.png');
  } else {
    next();
  }
}

Is it worth adding this to the docs to showcase to others how it can be solved?

oemer-aran commented 6 months ago

I have another issue where the user could upload a corrupted jpg file, IPX will throw an error at this case, since it can't parse the meta data to optimize the image. Can I fallback to the original image in this case?

Essentially I need to hook into the response of an ipx call in my nuxt-app. If the ipx call fails, i first want to try to get the original image and if that fails too, send an error. Is that possible?