unjs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.unjs.io
MIT License
5.89k stars 496 forks source link

Unable to serve assets from a cached event handler in server. #2679

Closed amandesai01 closed 4 weeks ago

amandesai01 commented 1 month ago

Basically, I want to serve assets from a event handler in server. Questions:

  1. Is it worth adding caching for static assets?
  2. If yes, I am facing below issue. When cached handler is called for first time, it returns asset directly and works fine. (Image in my case). Now, after caching, I believe that image is in the form of buffer and thus, gets stringified which is causing the issue. The handler than return stringified version of Buffer.
export default defineEventHandler(async (event) => { // THIS WORKS!
  const key = getRouterParam(event, "key"); 
  const asset = await blobStorage.getItemRaw(key);
  return asset;
});

export default defineCachedEventHandler(async (event) => { // THIS DOESN'T
  const key = getRouterParam(event, "key");
  const asset = await blobStorage.getItemRaw(key);
  return asset;
}, {
  maxAge: 60 * 60,
  getKey(event) {
    return getRouterParam(event, "key") || "";
  },
})

For full context, see: https://github.com/profilecity/vidur/blob/main/src/server/routes/assets/%5Bkey%5D.ts

Originally posted by @amandesai01 in https://github.com/unjs/nitro/discussions/2650

amandesai01 commented 4 weeks ago

Any updates on this? Do I need to provide something extra?

pi0 commented 4 weeks ago

Hi dear @amandesai01 this is a known limitation in Nitro v2 cache that binary responses are not catchable and it is not easily fixable to support all binary types.

The good news is that with the upcoming Nitro v3 and h3 caching would support it out of the box.

amandesai01 commented 4 weeks ago

Awesome! I will close this then.