How to define Middleware in Vue js?


Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Vuejs includes a middleware that verifies the user of your application is authenticated or not. All of these middleware are located in the src/middleware directory.

Syntax Of Routes.

Create a auth.js file inside middleware folder.

export default function auth(to, from, next) {
    if(localStorage.getItem("usertoken")){
        //this.$forceUpdate();
        return next();
    }else{
        next({ name: "login" });
    }
}
import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import { ContentLoader } from "vue-content-loader";
import VueRouteMiddleware from "vue-route-middleware";

import AuthMiddleware from "../middleware/auth";
import GuestMiddleware from "../middleware/guest";
import Login from "../components/Login.vue";
import Dashboard from "../components/admin/Dashboard";
import CatalogMain from "../../src/components/admin/catalog/CataLogMain";

Vue.config.productionTip = false;
Vue.use(VueRouter);

var mainRoute = [
    {
        path: "/login",
        name: "login",
        component: Login,
        meta: {
            middleware: [GuestMiddleware],
        },
    },
    {
        path: "/admin/dashboard",
        component: Dashboard,
        name: "admin.dashboard",
        meta: {
            middleware: [AuthMiddleware],
        },
    },
    {
        path: "/admin/catalog",
        component: CatalogMain,
        name: "admin.catalog",
        meta: {
            middleware: [AuthMiddleware],
        },
    },
];

const router = new VueRouter({
    mode: "history",
    base: __dirname,
    routes: mainRoute,
    linkActiveClass: "active",
    linkExactActiveClass: "exact-active",
});

router.beforeEach(VueRouteMiddleware({ GuestMiddleware }));

new Vue({
    router,
    render: (h) => h(App),
}).$mount("#app");