Search code examples
vue.jsroutesvue-componentvue-routermiddleware

How to create a middleware or how to manage the below route for front end and admin


How can I manage the url for front and admin panel Via Middleware in Vue.

This is the code I have written in router/index.js file:

const router = new VueRouter({ mode: 'history', routes });

  router.beforeEach((to, from, next) => {

  // redirect to login page if not logged in and trying to access a restricted page
  const loggedIn = localStorage.getItem('usertoken') == null ? false : true;
  const user = JSON.parse(localStorage.getItem('user'));

  //this is for admin
  next('/admin/login')
  next('/admin/home');

  //this is my front URL
  next('/terms-condition');
  next('/home');
  next()
})
export default router;

Solution

  • See the below code it may helps you

    /** * middleware for authentication */

    router.beforeEach((to, from, next) => {
    // redirect to login page if not logged in and trying to access a restricted page
      const loggedIn = localStorage.getItem('usertoken') == null ? false : true;
      const user = JSON.parse(localStorage.getItem('user'));
    
      if (to.meta.portal == 'admin') {
        if (to.meta.auth) {
            if (!loggedIn) {
                next('/admin/login')
            } else if (loggedIn) {
                next();
            }
        } else {
            if (!loggedIn) {
                next();
            } else if (loggedIn) {
                if (user.role_id == '1') {
                    next('/admin/home');
                } else {
                    next('/');
                }
            }
    
        }
      } else if (to.meta.portal == 'front') {
    
        if (loggedIn) {
    
            if (user.role_id == '1') {
                next('/admin/home');
            } else {
                next('/');
            }
    
        } else if (!loggedIn) {
            if (to.path == "/admin") {
                next('/admin/login');
            } else {
                next();
            }
        }
      }
     next()
    })
    
    export default router;
    

    And you need to create two router files one for front and other for admin:

    //front route file will look like

    export default [{
    path: '/',
    meta: { auth: false, portal: 'front' },
    component: () => import('@/components/layouts/front/main.vue'),
    children: [
        {
            path: '/',
            name: 'front-home',
            title: 'Dashboard',
            meta: { auth: false, portal: 'front' },
        }
       ]
    }]
    

    //admin router file will be like

    export default [
     {
        path: 'user',
        name: 'users',
        title: 'Users',
        meta: { auth: true, portal: 'admin' },
        component: () => import('@/components/templates/admin/user'),
     }
    ]
    

    Main difference is the portal that defines which portal will access by the respective route.Without portal inside meta it won't work.