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.
This commit is contained in:
parent
8329ff060b
commit
7f3029aee8
1 changed files with 33 additions and 8 deletions
|
@ -1,9 +1,34 @@
|
||||||
export const useAccountSession = () => useFetch(
|
import { appendResponseHeader } from "h3";
|
||||||
"/api/auth/session",
|
import type { H3Event } from "h3";
|
||||||
{
|
|
||||||
transform: (input) => input === undefined ? false as any as null: input,
|
const fetchWithCookie = async (url: string, event?: H3Event) => {
|
||||||
getCachedData(key, nuxtApp) {
|
if (!event) {
|
||||||
return nuxtApp.payload.data[key];
|
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",
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue