Within a vue 3 application utilizing the composition api, I need to implement different actions depending on whether an authenticated user is verified or not. If the user is not verified, they should be directed to the verification page. However, if the user is verified, they should be redirected to the dashboard.
To accomplish this, I have incorporated navigation guards in my router's index.js
file:
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/signin",
name: "signin",
component: () => import("../views/SignIn.vue"),
},
{
path: "/verify",
name: "verify",
component: () => import("../views/Verification.vue"),
meta: { needsAuth: true }
},
{
path: "/dashboard",
name: "dashboard",
component: () => import("../views/UserDashboard.vue"),
meta: { needsAuth: true },
beforeEnter: (to, from, next) => {
if (localStorage.getItem('verified') == "false") next('verify')
}
},
],
});
router.beforeEach(async (to, from, next) => {
if (to.meta.needsAuth && localStorage.getItem('accessToken') == null) next('signin')
else next()
})
export default router
In the script setup of my signin page, I've included the following code:
import { ref } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
const router = useRouter();
const signin = ref({
email: null,
password: null,
});
const loginUser = async () => {
try {
const res = await axios.post(
"https://mydomain/api/login",
signin.value,
{
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
}
);
localStorage.setItem("accessToken", res.data.data.accessToken);
localStorage.setItem("verified", res.data.data.verified);
router.push({ name: "dashboard" });
} catch (error) {
alert(error.response.data.message);
}
};
Upon logging in with an unverified user, I am successfully redirected to the verification page as expected. However, when logging in with a verified user, I remain on the signin view instead of being directed to the dashboard.
I am unsure of what could be causing this issue. How can I resolve this routing problem?