Navigation guard for dynamic route

Viewed 18

I have navigation guards to prevent visitors from viewing protected pages without being logged in. One of the pages I want them to see without login is a dynamic route e.g. example.com/dynamic_part. Below is my vuejs code:

router.beforeEach((to, from, next) => {
  let token = window.sessionStorage.getItem("local_token");

  let whitelist = [
    "/",
    "/register",
    "/login",
    "/dynamic_part/",
  ];

below works but it doesn't allow for the dynamic route "/dynamic_part/"

  if (whitelist.includes(to.path)) {

below works for the dynamic route but breaks other route guards i.e. can't move to Products after logging in. I get this error: Error: Redirected when going from "/login" to "/Products" via a navigation guard.

whitelist.some(item => console.log(to.path.includes(item), item))
if (whitelist.some(item => to.path.includes(item))) {

The rest of the navigation guard:


    if (token) {
      next({
        name: "Products",
      });
    } else {
      next();
    }
  } else {

    if (token) {
      next();
    } else {
      next({
        name: "Login",
      });
    }
  }
});

What am I doing wrong and how can get all urls to work?

1 Answers

The problem here is all routes will match to.path.includes("/"). You need to separate the routes you want to match fully, with the ones you match with contains (you might want startsWith()?).

const whitelist = [
    "/",
    "/register",
    "/login",
  ];
const dynamicWhitelist = [
    "/dynamic_part/",
];

if (whitelist.includes(to.path) || dynamicWhitelist.some(item => to.path.includes(item))) {
    /// etc
}

The more 'Vue-router-like' way of doing this is defining a meta object in your routes and testing against those.

//routes:
const routes = [
{
    path: '/login',
    component: Login,
    meta: { allowAnon: true }
}
...
router.beforeEach((to, from, next) => {
    let token = window.sessionStorage.getItem("local_token");

    if(to.meta.allowAnon) {
        //etc

See the docs here for more details.

Related