In a vue 3 application that uses composition api, I want to do one of 2 things based on if an authenticated user is verified or not. So if the user is not verified, send the user to the verification page. But if the user is verified, send the user to the dashboard.
To achieve this, I am using navigation guards in my router index.js
like this
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
Then in my sigin page script setup
, I have 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); } };
Now when I login with an unverified user, I get redirected to the verification page as intended. But when I login with a verified user, I never get sent to the dashboard and instead the app remains on the signin view.
I can’t seem to figure out what the problem is. How can I fix this routing issue?
Advertisement
Answer
Did you try with next()
if user is verified:
beforeEnter: (to, from, next) => { if (localStorage.getItem('verified') == "false") next('verify') else next() }