From 7f3029aee82b3d3e01c19a7560f78059c6ce4efa Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Fri, 23 May 2025 21:32:20 +0200 Subject: [PATCH] Pass Set-Cookie header from session on page load If a session is refreshed when accessed through /api/auth/session during a SSR then the Set-Cookie header was lost. Pass this along to the client in this case to keep the session alive. --- composables/session.ts | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/composables/session.ts b/composables/session.ts index 407bfe4..d335555 100644 --- a/composables/session.ts +++ b/composables/session.ts @@ -1,9 +1,34 @@ -export const useAccountSession = () => useFetch( - "/api/auth/session", - { - transform: (input) => input === undefined ? false as any as null: input, - getCachedData(key, nuxtApp) { - return nuxtApp.payload.data[key]; - }, +import { appendResponseHeader } from "h3"; +import type { H3Event } from "h3"; + +const fetchWithCookie = async (url: string, event?: H3Event) => { + if (!event) { + return $fetch(url); } -); + + const cookie = useRequestHeader("cookie"); + const res = await $fetch.raw(url, { + headers: cookie ? { cookie } : undefined + }); + for (const cookie of res.headers.getSetCookie()) { + appendResponseHeader(event, "set-cookie", cookie); + } + return res._data; +} + +export const useAccountSession = () => { + const event = useRequestEvent(); + return useAsyncData( + "session", + async () => await fetchWithCookie("/api/auth/session", event), + { + transform: (input) => input === undefined ? false as any as null: input, + getCachedData(key, nuxtApp, context) { + if (context.cause === "refresh:manual") + return undefined + return nuxtApp.payload.data[key]; + }, + dedupe: "defer", + } + ); +}