diff --git a/packages/nuxt/src/app/composables/cookie.ts b/packages/nuxt/src/app/composables/cookie.ts index 99b0392f8e..532e28bd85 100644 --- a/packages/nuxt/src/app/composables/cookie.ts +++ b/packages/nuxt/src/app/composables/cookie.ts @@ -140,22 +140,43 @@ function writeServerCookie (event: H3Event, name: string, value: any, opts: Cook } } +/** + * The maximum value allowed on a timeout delay. + * + * Reference: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value + */ +const MAX_TIMEOUT_DELAY = 2_147_483_647 + // 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) }) + let elapsed = 0 + if (getCurrentScope()) { + onScopeDispose(() => { clearTimeout(timeout) }) + } + return customRef((track, trigger) => { + function createExpirationTimeout () { + clearTimeout(timeout) + const timeRemaining = delay - elapsed + const timeoutLength = timeRemaining < MAX_TIMEOUT_DELAY ? timeRemaining : MAX_TIMEOUT_DELAY + timeout = setTimeout(() => { + elapsed += timeoutLength + if (elapsed < delay) { return createExpirationTimeout() } + + value = undefined + trigger() + }, timeoutLength) + } + return { get () { track() return value }, set (newValue) { - clearTimeout(timeout) - timeout = setTimeout(() => { - value = undefined - trigger() - }, delay) + createExpirationTimeout() + value = newValue trigger() }