In Nitro (and thus in Nuxt 3 server API routes), the options object for defineCachedEventHandler is static and evaluated at the time the handler is defined, not per request. This means you cannot directly use dynamic values like query parameters (e.g., lang) in the name property as you attempted:
name: `suggestions-${lang}`
However, Nitro provides a way to customize the cache key per request using the getKey option. The getKey function receives the event and allows you to return a string that will be used as the cache key. This is the correct way to include dynamic values such as the current language in your cache key.
Here’s how you can do it:
import { fetchSuggestions } from '../utils/suggestions'
export default defineCachedEventHandler(async (event) => {
const query = getQuery(event)
const lang = query.lang as string || ''
return await fetchSuggestions(lang)
}, {
getKey: (event) => {
const query = getQuery(event)
const lang = query.lang as string || ''
return `suggestions-${lang}`
},
maxAge: 86400,
swr: true,
})
This way, the cache will be separated for each language, as the cache key will be different depending on the lang query parameter.
The knowledge sources do not explicitly mention the getKey option for defineCachedEventHandler, but based on the available documentation and common Nitro patterns, this is the standard approach. If you need further confirmation, please refer to the latest Nitro or Nuxt documentation or source code for defineCachedEventHandler options.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: