custom `name` parameter for Nitro `defineCachedEventHandler()`
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:
How can
name receive a value depending on the query parameters?2 Replies
Hi @enti. 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:
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:
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:
----------------------
<@210882495707742219> Kapa.ai is still learning and improving, please let me know how I did by reacting below.