How to prevent Nuxt state being serialized to DOM and served from CDN cache?

I need help about Nuxt that would help me prevent some of our SSR (Server-Side Rendered) pages when user information has been fetched and stored in our pinia store being cached.

Problem: Currently, when we do SSR, we fetch user data during page generation and some of the user information gets serialized to __NUXT_DATA__ so it can be picked up during hydration on the client.

We also use a CDN to speed up our pages and prevent the servers from being overloaded with requests. The issue is that the CDN caches the page content and that includes __NUXT_DATA__ which is not good: the __NUXT_DATA__ state that is cached might be the state of another visitor of the website. We can’t disable the CDN cache on pages where this happen as this would disable cache everywhere.

Solutions tried:

  • We read nuxt docs & code to find a way of disabling the serialization of the pinia store to __NUXT_DATA__, but couldn’t find any.
  • We tried creating a nuxt middleware to check the store & add cache-control headers but we either…:
    • could not get the request (useRequestEvent() would return undefined)
    • would be too early reading the pinia store (even when being the last middleware to run), so the state would be later updated with user info and the proper cache headers not applied (and thus missing).
  • We tried to catch the pinia store state at the end of the SSR and add Cache-Control headers if the pinia store state contains user data. When we tried this with a nitro server plugin and hooking on the render:response event, the server would crash as nitro can’t access nuxt or pinia stores (we use composables so we would import useMyStore() in the nitro server plugin.

Question:

  • How can we disable pinia getting serialized to __NUXT_DATA__ between SSR and client hydration ?
  • OR How can we read a pinia store and add Cache-Control headers conditionally to the response if the store has a given state ?

Thanks for any help or pointers you can have about this !

Additional info:

  • nuxt version: 3.10
  • pinia version: 2.2.6