Vitor
Vitor
NNuxt
Created by Vitor on 7/11/2024 in #❓・help
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,
});
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);
}
}
});
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!
3 replies