Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
Protect a vue route with multiple guards

I have a vue router like this:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

function guard (to, from, next) {
  if (localStorage.getItem('jwt')) {
    next()
  } else {
    next('/login')
  }
}

function admin (to, from, next) {
  if (localStorage.getItem('admin') && localStorage.getItem('admin') !== 'false' && localStorage.getItem('jwt')) {
    next()
  } else {
    next('/noadmin')
  }
}

export default new Router({

  mode: 'history',

  routes: [
    {
      path: '/',
      name: 'home',
      beforeEnter: guard,
      meta: { layout: 'default' },
      component: () => import('@/components/dashboard.vue')
    },
    {
      path: '/datacollector',
      name: 'datacollector',
      beforeEnter: guard,
      meta: { layout: 'default' },
      component: () => import('@/components/datacollector.vue')
    },
    {
      path: '/licensing',
      beforeEnter: admin,
      name: 'licensing',
      component: () => import('@/components/licensing.vue')
    },
    {
      path: '*',
      name: '404',
      component: require('@/pages/404.vue').default
    }
  ]

})

My problem now is the following, if there is an entry localStorage.getItem('datacollector') it should only point to the path /datacollector and /logout. So when he logs in, the login page throws him to the path /datacollector. But he should also be able to call logout. For the other users, it should be that they are allowed to call everything. How do I adjust the function guard, no matter what I try I always end up with a loop. Thank you.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Assuming you want to throw the user to /datacollector route from any route, if there is an entry for localStorage.getItem('datacollector'), except for /logout route.

You can simply check for to.path and redirect the user accordingly:

function guard (to, from, next) {
  if (localStorage.getItem('jwt')) {
    if (localStorage.getItem('datacollector')) {
      if (to.path != '/datacollector' && to.path != '/logout'){
        next('/datacollector');
      } else {
        next();
      }
    } else {
      next();
    }
  } else {
    next('/login')
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!