#custom `name` parameter for Nitro `defineCachedEventHandler()`

3 messages · Page 1 of 1 (latest)

forest lion
#

I want to use the current language as a parameter sor my API call. Obviously, I want my cache strategy to follow these different languages possibilities:

import { fetchSuggestions } from '../utils/suggestions'

export default defineCachedEventHandler(async (event) => {
  const query = getQuery(event)
  const lang = query.lang as string || ''

  return await fetchSuggestions(
    lang,
  )
}, {
  name: `suggestions-${lang}`, // won't work, but what will ?
  maxAge: 86400, // 24h
  swr: true,
})

How can name receive a value depending on the query parameters?

haughty sunBOT
#

Hi @forest lion. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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}` // This won't work, as lang is not available here

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, // 24h
  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: