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

feat(defineCachedEventHandler): add `event.context.cache` #2519

Closed atinux closed 3 months ago

atinux commented 3 months ago

This allow the frontend framework connected to Nitro to be aware that the page is cached, useful for handling a flag in the payload to handle a different logic on client-side (e.g: fetch the auth state after hydration)

pi0 commented 3 months ago

Thanks for PR. I thibnk we should make it to context.cache: {} to preserve more cache state. (#2520)

atinux commented 3 months ago

Updated to set cache as empty object to start, we can follow up later in other pull requests.

Also added a basic test case to improve later on too.

meirroth commented 3 months ago

Hi @Atinux, Is this feature planned for Nuxt, or is it a use case you are developing? I'm curious to see how it can be used. I believe this can be very helpful for caching heavy pages while keeping them dynamic for users.

pi0 commented 3 months ago

@meirroth You can access the same event.cache.option object from Nuxt server routes also optionally use a Nitro plugin + hooks to expose it via SSR payload to the client side.

This feature initially has two usecases:

Dynamically enabling or disabling cache can be done using shouldBypassCache option.

manniL commented 3 months ago

And for "nuxt-rendered" parts (so no server api / server routes), https://github.com/nuxt/nuxt/issues/26598 is where we track it.

meirroth commented 3 months ago

@pi0 and @manniL, thank you for your replies!

I'm trying to understand how to apply this in practice, so an example would be really helpful if you have one.

My use case involves caching a page with SWR for all except requests with an auth header. This way, visitors will see a cached page, while logged-in users will see a personalized version of the page, which differs for each user.

I just watched @manniL's video on Dynamic Rendering SSR/SPA. (Great video as always!) Is the approach similar? Would it involve defining server middleware that checks for an auth header and, if it exists, disables the cache with event.cache.option?

Additionally, I assume the i18n module adds complexity since you'd need to cache pages for each language.