Refreshing token with Pinia and Vue Router

Viewed 31

I just started working with Vue and I'm not sure how to protect routes on the front. I created a login ACTION that sends the token to Local Storage and then I want that every time the user tries to access a protected route the router needs to check if the token is still valid.

I think I'm missing this asynchronous request, but I can't solve it. Does anyone have any tips?

async refresh(token) {
            let isLogged = false;
            const response = await fetch("XXXXXXXXXX", {
                method: "GET",
                headers: {
                    "Content-type": "application/x-www-form-urlencoded",
                    "Token": `${token}`
                }
            })
            
            if (!response.ok) {
                return isLogged;
            };
            
            isLogged = true;
            
            return isLogged
        }


router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore();
    const token = localStorage.getItem('token');
    const isLogged = await authStore.refresh(token)
    
    
    if (to.meta.authRequired) {
        if (isLogged) {
            next();
        } else {
            next("/login");
        }
    } else {
        next();
    }


})
0 Answers
Related