Need URGENT help regarding useCookie issue

I have a issue that once I set cookie via SSR once it works fine. In the cookie I am setting JWT token value. I have made a plugin for api calls named httpClient which is under the hood is using axios where I am using axios interceptor for request and response to do dynamic stuff like passing token in request headers and stuff There is global middleware which checks if cookie doesnt exist then it calls internal nuxt api which is inside /server directory which is working fine. Now during SSR, I am calling two external APIs where I send JWT token in headers for authentication. Let's say my token has expired (not the cookie), then external API checks the token and gives new token in its response header which I am able to see in its response header but when I try to overwrite cookie value which holds expired token with new token value. Whether I try to do it in SSR or client side it doesn't let me overwrite value of the cookie which already is present while retaining it's expiry time. If i forcefully change the value like useCookie('access_token').value = newToken then it loses its expiry time and get converts to session based ANYONE WHO KNOWS THIS ISSUE PLEASE HELP? Your knowledge will be very valuable to me. I will share example code for those interested in solving this issue.
4 Replies
kapa.ai
kapa.ai2mo ago
Hi @Evascene_void. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- I understand your frustration with the useCookie issue in Nuxt. This is a known challenge when trying to update cookie values while maintaining their original properties. The Issue When you update a cookie value directly with useCookie('access_token').value = newToken, you're right that it loses its expiry time and other properties, converting it to a session cookie. This happens because simply updating the value doesn't preserve the original cookie options. Solution There are a few approaches to solve this: 1. Use the same options when updating the cookie When you initially set the cookie, store the same options object and use it when updating:
// When initially setting the cookie
const accessToken = useCookie('access_token', {
maxAge: 3600, // or whatever your expiry time is
secure: true,
// other options
});

// When updating
accessToken.value = newToken; // This will use the same options
// When initially setting the cookie
const accessToken = useCookie('access_token', {
maxAge: 3600, // or whatever your expiry time is
secure: true,
// other options
});

// When updating
accessToken.value = newToken; // This will use the same options
2. Use refreshCookie utility (Nuxt 3.10+) If you're using Nuxt 3.10 or later, you can use the refreshCookie utility to refresh the cookie value when it has changed:
// After receiving new token from API response
setCookie(event, 'access_token', newToken, {
// same options as before
});
refreshCookie('access_token');
// After receiving new token from API response
setCookie(event, 'access_token', newToken, {
// same options as before
});
refreshCookie('access_token');
This is particularly useful when the cookie is set in an API response and you need to update the useCookie ref value Nuxt docs on refreshCookie. 3. For API responses, append the Set-Cookie header If you're receiving the new token in an API response, you can append the Set-Cookie header directly:
const event = useRequestEvent();
const res = await $fetch('/api/auth/refresh', {
method: 'POST',
headers: useRequestHeaders(['cookie']),
onResponse({ response }) {
const cookies = response.headers.getSetCookie();

if (cookies.length) {
cookies.forEach((cookie) => {
if (event) {
appendResponseHeader(event, 'set-cookie', cookie);
}
});
}
},
});
const event = useRequestEvent();
const res = await $fetch('/api/auth/refresh', {
method: 'POST',
headers: useRequestHeaders(['cookie']),
onResponse({ response }) {
const cookies = response.headers.getSetCookie();

if (cookies.length) {
cookies.forEach((cookie) => {
if (event) {
appendResponseHeader(event, 'set-cookie', cookie);
}
});
}
},
});
This approach preserves all cookie properties from the response Stack Overflow solution. Common Issues to Watch For 1. Be aware that Nuxt prevents duplicate set-cookie headers when the value is unchanged to avoid issues. 2. If you're setting cookies in server API routes, use getCookie and setCookie from the h3 package:
export default defineEventHandler(event => {
// Read token cookie
let token = getCookie(event, 'access_token')

// Update token cookie
setCookie(event, 'access_token', newToken, {
maxAge: 3600,
// other options
})
})
export default defineEventHandler(event => {
// Read token cookie
let token = getCookie(event, 'access_token')

// Update token cookie
setCookie(event, 'access_token', newToken, {
maxAge: 3600,
// other options
})
})
Nuxt docs on Cookies in API Routes I hope this helps resolve your issue with updating the JWT token while preserving the cookie's expiry time! ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2mo ago
<@719787055789506632> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Evascene_void
Evascene_voidOP2mo ago
Dynamic cookie setting is happening in the httpclient plugin which is inside root directory /plugins folder. Not in the server/ folder
Evascene_void
Evascene_voidOP2mo ago
SOLVED Answer: To retain expiry time then const testCookie = useCookie("test", {   expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30), }); testCookie.value = newValue
And then update the cookie value then expiration date is maintained. https://www.reddit.com/r/Nuxt/s/0sYPyfwloq
Reddit
From the Nuxt community on Reddit
Explore this post and more from the Nuxt community

Did you find this page helpful?