Search code examples
javascriptlocal-storagesveltesveltekitsvelte-3

Cannot access localstorage from sveltekit hook


I've got a function that verifies whether an user is logged in or not:

export const isUserLoggedIn = () => {

    let dmcAuthToken = localStorage.getItem(AUTH_TOKEN_KEY);

    return dmcAuthToken ? true : false;

}

when an user logs in, local storage is updated with a token returned from the backend:

localStorage.setItem(AUTH_TOKEN_KEY, dmcAuthToken);

Now, I'm trying to restrict access to pages when the user is not logged, I've read a bit and found a hook called handle so I decided to implement this logic there:

/src/hooks.js:

export async function handle({ event, resolve }) {

    if (!isUserLoggedIn() && event.url.pathname != "/login") {
        console.log("user NOT logged in");
        return new Response(null, {
            status: 302,
            headers: {
                location: "/login"
            }
        })
    }

    if (isUserLoggedIn() && event.url.pathname == "/login") {
        return new Response(null, {
            status: 302,
            headers: {
                location: "/pos"
            }
        })
    }

    return resolve(event);
}

But I'm getting an error: 500 localStorage is not defined

any idea what's going on?

For testing, if I return either true or false from isUserLoggedIn the implemented logic in the hook seems to work, but the issue is when trying to access localStorage, why is that?

I've seen solution where the token is saved in a store but don't wanna go that route unless it's necessary, I'd like to know why my way isn't working.

Thanks


Solution

  • that's because localStorage is not available on the server side

    please use cookie to save token