Ryan
Ryan
NNuxt
Created by Ryan on 11/22/2024 in #❓・help
Do Nuxt server plugins (example.server.ts) execute on every request for a SWR cached route?
Hello, during development and in my local production build I can see that the Nuxt server plugin I've created is executing on every request I make (even if the route is cached), however in my Vercel deployment it does not. This results in sensitive data being leaked across requests. It would be great to know if this is correct behaviour or if I've missed something. Any help would be greatly appreciated! Route rule:
'/': { swr: 3600, cache: { varies: ['x-variant'] } }
'/': { swr: 3600, cache: { varies: ['x-variant'] } }
Example plugin:
import { defineNuxtPlugin, useCookie, useRuntimeConfig, useState } from '#app'

export default defineNuxtPlugin({
name: 'test-server-plugin',
enforce: 'pre',
setup: async (nuxtApp) => {
const identity = useCookie('test-cookie-id', { default: () => '' })

if (nuxtApp.ssrContext?.event.context.exampleId) {
identity.value = exampleId
}

useState<Record<string, boolean | string> | undefined>('test-state-server', () => nuxtApp.ssrContext?.event.context.exampleFlags)
},
})
import { defineNuxtPlugin, useCookie, useRuntimeConfig, useState } from '#app'

export default defineNuxtPlugin({
name: 'test-server-plugin',
enforce: 'pre',
setup: async (nuxtApp) => {
const identity = useCookie('test-cookie-id', { default: () => '' })

if (nuxtApp.ssrContext?.event.context.exampleId) {
identity.value = exampleId
}

useState<Record<string, boolean | string> | undefined>('test-state-server', () => nuxtApp.ssrContext?.event.context.exampleFlags)
},
})
Further context: Supporting SSR & caching with feature flags. We want to cache depending on the feature flag variant used on that page. Server middleware: - Read ID from cookie or generate ID in server middleware - Load flags with the ID - If a flag matches the route, set that value in a custom header so we can generate new cached responses from it using varies. - Set ID & flags we want to use to generate the page(s) from in the event context so we can use it in the server context without refetching Nuxt server-side plugin: - Read ID and flags, set ID in the cookie & flags into state Client side: - Use state to generate page
5 replies