How to Add an Auth Middleware with Vue-router
In this lesson we are going to see how to make an auth middleware using vue-router, the middleware will check if the user is logged in before accessing the route.
Create the route guard
Let's assume that we have a profile page and the user must be logged in to access this page.
We can use a route guard that checks if the user is logged in.
In the code below inside the router, we import a store with Pinia that returns a login status equal to true or false, and we check if the user is logged in he is ok to go if not he is redirected to the login page.
import {createRouter, createWebHistory} from 'vue-router';
import Profile from '@/components/Profile.vue';
import { useAuthStore } from '@/store/useAuthStore';
function checkIfLogged() {
const authStore = useAuthStore();
if (!authStore.getLoggedInstatus) return '/login';
}
const routes = [
{
name: 'profile',
path: '/user/profile',
component: Profile,
beforeEnter: [checkIfLogged],
}
]
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;