Using useCookie inside onRequest
is it safety to use
useCookie
inside onRequest
?
it only works this way, if I move it up new requests doesn't get new cookie value2 Replies
Hi @salomon_.. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Yes, it's safe to use
useCookie
inside the onRequest
handler in your Nuxt plugin. This approach ensures that you're getting the most up-to-date cookie value for each request.
When you place useCookie
inside the onRequest
handler, it will be called each time a request is made, allowing your code to access the current value of the cookie. This is particularly important for cookies that might change during the application lifecycle.
If you were to move the useCookie
call outside the onRequest
handler (at the plugin level), it would only be evaluated once when the plugin initializes, and wouldn't reflect any changes to the cookie that happen later.
For server-side requests, it's worth noting that Nuxt has special handling for cookies. When using useFetch
with a relative URL on the server, Nuxt will use useRequestFetch
to proxy headers and cookies automatically Passing Headers and Cookies.
If you need to manually refresh cookie values when they change (for example, after an API call that sets a cookie), you can use the refreshCookie
utility that was introduced in Nuxt 3.10:
This will update the value returned by useCookie
without waiting for the next request refreshCookie.
Your implementation looks correct and follows good practices for handling localization headers based on cookies in Nuxt.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@1029431292170874910> Kapa.ai is still learning and improving, please let me know how I did by reacting below.