mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-22 05:35:13 +00:00
fix(nuxt): prevent duplicate set-cookie
headers (#28211)
This commit is contained in:
parent
064e7b7f12
commit
58f4f47791
@ -126,6 +126,16 @@ export function useCookie<T = string | null | undefined> (name: string, _opts?:
|
||||
const nuxtApp = useNuxtApp()
|
||||
const writeFinalCookieValue = () => {
|
||||
if (opts.readonly || isEqual(cookie.value, cookies[name])) { return }
|
||||
nuxtApp._cookies ||= {}
|
||||
if (name in nuxtApp._cookies) {
|
||||
// do not append a second `set-cookie` header
|
||||
if (isEqual(cookie.value, nuxtApp._cookies[name])) { return }
|
||||
// warn in dev mode
|
||||
if (import.meta.dev) {
|
||||
console.warn(`[nuxt] cookie \`${name}\` was previously set to \`${opts.encode(nuxtApp._cookies[name] as any)}\` and is being overridden to \`${opts.encode(cookie.value as any)}\`. This may cause unexpected issues.`)
|
||||
}
|
||||
}
|
||||
nuxtApp._cookies[name] = cookie.value
|
||||
writeServerCookie(useRequestEvent(nuxtApp)!, name, cookie.value, opts as CookieOptions<any>)
|
||||
}
|
||||
const unhook = nuxtApp.hooks.hookOnce('app:rendered', writeFinalCookieValue)
|
||||
|
@ -112,6 +112,8 @@ interface _NuxtApp {
|
||||
|
||||
[key: string]: unknown
|
||||
|
||||
/** @internal */
|
||||
_cookies?: Record<string, unknown>
|
||||
/** @internal */
|
||||
_id?: number
|
||||
/** @internal */
|
||||
|
3
test/fixtures/basic/pages/cookies.vue
vendored
3
test/fixtures/basic/pages/cookies.vue
vendored
@ -9,6 +9,8 @@ useCookie<string | null>('set-to-null-with-default', { default: () => 'default'
|
||||
useCookie('browser-accessed-but-not-used')
|
||||
useCookie('browser-accessed-with-default-value', { default: () => 'default' })
|
||||
useCookie('browser-set').value = 'set'
|
||||
// confirm that it only sets one `set-cookie` header
|
||||
useCookie('browser-set').value = 'set'
|
||||
useCookie('browser-set-to-null').value = null
|
||||
useCookie<string | null>('browser-set-to-null-with-default', { default: () => 'default' }).value = null
|
||||
|
||||
@ -17,7 +19,6 @@ const objectCookieSecond = useCookie('browser-object-default', {
|
||||
default: () => ({ foo: 'bar' }),
|
||||
})
|
||||
function changeCookie () {
|
||||
console.log(objectCookie.value, objectCookieSecond.value)
|
||||
if (objectCookie.value!.foo === 'baz') {
|
||||
objectCookie.value!.foo = 'bar'
|
||||
} else {
|
||||
|
Loading…
Reference in New Issue
Block a user