Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(nuxt): stringify cookie values before broadcasting them #23449

Merged
merged 8 commits into from
Sep 29, 2023
12 changes: 6 additions & 6 deletions packages/nuxt/src/app/composables/cookie.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Ref } from 'vue'
import { getCurrentInstance, nextTick, onUnmounted, ref, toRaw, watch } from 'vue'
import { getCurrentInstance, nextTick, onUnmounted, ref, watch } from 'vue'
import type { CookieParseOptions, CookieSerializeOptions } from 'cookie-es'
import { parse, serialize } from 'cookie-es'
import { deleteCookie, getCookie, getRequestHeader, setCookie } from 'h3'
Expand All @@ -20,12 +20,12 @@ export interface CookieOptions<T = any> extends _CookieOptions {

export interface CookieRef<T> extends Ref<T> {}

const CookieDefaults: CookieOptions<any> = {
const CookieDefaults = {
path: '/',
watch: true,
decode: val => destr(decodeURIComponent(val)),
encode: val => encodeURIComponent(typeof val === 'string' ? val : JSON.stringify(val))
}
} satisfies CookieOptions<any>

export function useCookie<T = string | null | undefined> (name: string, _opts?: CookieOptions<T>): CookieRef<T> {
const opts = { ...CookieDefaults, ..._opts }
Expand All @@ -39,15 +39,15 @@ export function useCookie<T = string | null | undefined> (name: string, _opts?:

const callback = () => {
writeClientCookie(name, cookie.value, opts as CookieSerializeOptions)
channel?.postMessage(toRaw(cookie.value))
channel?.postMessage(opts.encode(cookie.value as T))
}

let watchPaused = false

if (channel) {
channel.onmessage = (event) => {
watchPaused = true
cookie.value = event.data
cookie.value = opts.decode(event.data)
nextTick(() => { watchPaused = false })
}
}
Expand All @@ -65,7 +65,7 @@ export function useCookie<T = string | null | undefined> (name: string, _opts?:
const nuxtApp = useNuxtApp()
const writeFinalCookieValue = () => {
if (!isEqual(cookie.value, cookies[name])) {
writeServerCookie(useRequestEvent(nuxtApp), name, cookie.value, opts)
writeServerCookie(useRequestEvent(nuxtApp), name, cookie.value, opts as CookieOptions<any>)
}
}
const unhook = nuxtApp.hooks.hookOnce('app:rendered', writeFinalCookieValue)
Expand Down