nuxt-multi-cache icon indicating copy to clipboard operation
nuxt-multi-cache copied to clipboard

Server response is never served from cache when using the fs driver

Open bgondy opened this issue 1 year ago • 0 comments

When using the fs driver for route caching, my page is never served from cache (cache miss). It seems the server overwrites the cache entry on every request (I can see the file).

✔ Vite server hmr 9 files in 18.635ms
[nuxt-multi-cache] ℹ Storing route in cache: /test-route/some-slug { expires: undefined, cacheTags: [], statusCode: 200 }
[nuxt-multi-cache] ℹ Storing route in cache: /test-route/some-slug { expires: undefined, cacheTags: [], statusCode: 200 }
[nuxt-multi-cache] ℹ Storing route in cache: /test-route/some-slug { expires: undefined, cacheTags: [], statusCode: 200 }
[nuxt-multi-cache] ℹ Storing route in cache: /test-route/some-slug { expires: undefined, cacheTags: [], statusCode: 200 }

I think the serveCachedRoute server handler is not working as expected. In my use case,cachedRaw is a Buffer instance, not a string, which explains why the following if statement (L34) is evaluated to false and the cache entry is not sent as response, falling back to a regular page render.

https://github.com/dulnan/nuxt-multi-cache/blob/057acca447f5bf17e81528f9397c1494ff1b1b95/src/runtime/serverHandler/serveCachedRoute.ts#L33-L34

In unstorage source code:

  • At storage level, getItemRaw() uses deserializeRaw() internally and may return a Buffer (https://github.com/unjs/unstorage/blob/9a31b658c807d28969b561db639e72a78698301b/src/_utils.ts#L76)
  • In the fs driver, getItemRaw() returns a Buffer when there is no encoding specified (see fs.readFile())

This can be a regression related #21.

A quick fix could be to convert the Buffer to a string, but I'm not aware of the possible side effects.

bgondy avatar Apr 25 '24 14:04 bgondy