NuxtN
Nuxt2y ago
Vitor

Middleware http-only cookies validation

Hi! I am trying to validate cookies on my middleware following an http-only cookies authentication strategy to restrict access to certain routes for authenticated users. For non-authenticated users it works perfect but for authenticated users, if they directly type the url or reload the page when in a protected route, as cookies are http-only it doesn't send them and navigates to '/'. If i use useFetch with server: false, it does not interrupt navigation to the page itself for unauthenticated users, it denies access but once on the route, crashing the page. Also tried this, which results on hydration conflicts:
const nuxtApp = useNuxtApp();
const fetchFunction = nuxtApp.ssrContext ? useFetch : $fetch;

await fetchFunction('/api/auth', {
    method: 'GET',
    credentials: 'include',
    server: false,
});


current middleware:
/middleware/auth.global.js
export default defineNuxtRouteMiddleware(async (to, from) => {
    const { areWeHandlingSessionStore, authFlowStore } = useHandlingSession();
    const freeRoutes = ['/', '/docs', '/legal', '/welcome'];

    if (!freeRoutes.includes(to.path)) {
        try {
            await $fetch('/api/auth', {
                method: 'GET',
                credentials: 'include',
            });
        } catch (error) {
            if (error.response?.status === 402) {
                authFlowStore.value = 'wall';
            } else if (error.response?.status === 403) {
                authFlowStore.value = 'resend';
            }
            areWeHandlingSessionStore.value = true;
            const redirectTo = freeRoutes.includes(from.path) ? from.path : '/';
            return navigateTo(redirectTo);
        }
    }
});


thanks in advance!
Was this page helpful?