From 6c48f8b8e6c5a790cfbdfe90d2694f35053bf75b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20G=C5=82owala?= Date: Fri, 3 Nov 2023 17:20:15 +0100 Subject: [PATCH] =?UTF-8?q?fix(nuxt):=20account=20for=20delay=20=E2=89=A4?= =?UTF-8?q?=200=20in=20`useCookie`=20(#24043)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/nuxt/src/app/composables/cookie.ts | 23 ++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/packages/nuxt/src/app/composables/cookie.ts b/packages/nuxt/src/app/composables/cookie.ts index 9b8d6c6485..99b0392f8e 100644 --- a/packages/nuxt/src/app/composables/cookie.ts +++ b/packages/nuxt/src/app/composables/cookie.ts @@ -32,16 +32,25 @@ export function useCookie (name: string, _opts?: const cookies = readRawCookies(opts) || {} let delay: number | undefined - if (opts.maxAge) { + + if (opts.maxAge !== undefined) { delay = opts.maxAge * 1000 // convert to ms for setTimeout } else if (opts.expires) { - // getTime() already return time in ms + // getTime() already returns time in ms delay = opts.expires.getTime() - Date.now() } - // use customRef if on client side otherwise use basic ref - const cookie = import.meta.client && delay - ? cookieRef((cookies[name] as any) ?? opts.default?.(), delay) - : ref((cookies[name] as any) ?? opts.default?.()) + + const hasExpired = delay !== undefined && delay <= 0 + const cookieValue = hasExpired ? undefined : (cookies[name] as any) ?? opts.default?.() + + // use a custom ref to expire the cookie on client side otherwise use basic ref + const cookie = import.meta.client && delay && !hasExpired + ? cookieRef(cookieValue, delay) + : ref(cookieValue) + + if (import.meta.dev && hasExpired) { + console.warn(`[nuxt] not setting cookie \`${name}\` as it has already expired.`) + } if (import.meta.client) { const channel = typeof BroadcastChannel === 'undefined' ? null : new BroadcastChannel(`nuxt:cookies:${name}`) @@ -131,7 +140,7 @@ function writeServerCookie (event: H3Event, name: string, value: any, opts: Cook } } -// custom ref that will update the value to undefined if the cookie expire +// custom ref that will update the value to undefined if the cookie expires function cookieRef (value: T | undefined, delay: number) { let timeout: NodeJS.Timeout onScopeDispose(() => { clearTimeout(timeout) })