Leo
Leo
NNuxt
Created by Leo on 10/30/2024 in #❓・help
No Cookies sent in Header?
@kapa.ai Can you refer to the following code? I'm not sure how I can implement your suggestions and still keep my custom fetch. Or are there other options? export default defineNuxtPlugin((nuxtApp) => { const api = $fetch.create({ baseURL: ${useRuntimeConfig().public.backendUrl}, credentials: 'include', async onRequest({ options }) { const accessTokenCookie = useCookie('access_token'); const { renewAuth, isTokenExpired } = useAuth(); const { obtainToken } = useCsrf(); const headers = options.headers;
if (!useCookie('csrf_token').value) { await obtainToken(); } const cookies = process.server ? useRequestHeaders(['cookie']) : null; debugger; if (useCookie('refresh_token').value) { if (isTokenExpired(accessTokenCookie.value as string)) { if (!(await renewAuth())) { await nuxtApp.runWithContext(() => navigateTo('/login') ); return; } } headers.set( 'Authorization', Bearer ${accessTokenCookie.value} ); } }, async onResponseError({ response, options }) { if (response.status == 401) { useCookie('access_token').value = null; useCookie('refresh_token').value = null; await nuxtApp.runWithContext(() => navigateTo('/login')); } }, }); return { provide: { api, }, }; });
13 replies