SvelteKit auth logic in hook keeps redirecting

Viewed 81

Am having a really weird issue with SvelteKit hooks, I have been dealing with this problem, even in my previous project, I had to rewrite my auth logic at the last moment right before launching.

I checked this question, and is somewhat related, but the issue am having is that everything run as intended in development, but when I run npm run build and run npm run preview (or deploy to netlify) then my site start acting up, when you visit the dashboard page with a session cookie, the page will be stuck in a continuously redirect, but without going somewhere.

hooks.ts

import type { GetSession, Handle } from "@sveltejs/kit";
import { parse } from "cookie"

export const handle: Handle = async ({ event, resolve }) => {
    const path = event.url.pathname;
    const accessToken = parse(event.request.headers.get('cookie') || "")?.access_token;

    event.locals.access_token = accessToken;

    if (path.startsWith('/dashboard') && !accessToken) {
        return new Response(null, {
            status: 302,
            headers: {
                location: "/login?next=" + path
            }
        })
    }

    if ((path.startsWith('/login') || path.startsWith('/register')) && accessToken) {
        return new Response(null, {
            status: 302,
            headers: {
                location: "/dashboard"
            }
        })
    }

    return await resolve(event)
}


export const getSession: GetSession = ({ locals }) => {
    return {
        logged_id: locals.access_token !== undefined
    }
}

I have also replicated a full working demo of the error here

0 Answers
Related