Vue router redirects to 404 instead of login page (Nuxt.js)

Viewed 724

I'm expiriencing a weird behavior in a Nuxt.js project with Vue router: I'm trying to use a route guard that is placed in route.js plugin, it's registered in the nuxt.config.js plugins section and it looks like this:

  app.router.beforeEach((to, from, next) => {
    to.name !== "login" && app.store.getters["session/token"] === ""
      ? next({ name: "login" })
      : next();
  });

The idea is, if a user refreshes the page he loses the token that is stored in the Vuex session module, so he should be redirected to the login page.

The weird behavior is - the route guard practically works, it redirects to the /login url, but it displays the 404 page - if i refresh the page again, it correctly redirects to the /login url/page.

I also tried directly pushing to the login page app.router.push({ name: "login" }), but to no avail.

A workaround i did is adding redirect in the 404 page:

  beforeCreate() {
    this.$router.push({ name: "login" });
  },

but i'm not happy with it...

Does anyone have any idea what's going on?

2 Answers

Some time ago, I created similar behavior in a Vue.JS project. Here's my code, maybe it helps you find the bug.

// checks if user is authenticated before displaying the page
// if not, reroutes to the login page

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (store.getters.isAuthenticated) {
      next();
      return;
    }
    next('/login');
  } else {
    next();
  }
});

The meta field defines if authentication is needed or not. In the code snippet below, you can see how its used.

const routes = [
  {
    path: '/',
    component: DashboardLayout,
    redirect: '/login',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          requiresAuth: true,
        },
      }
    ]
  }
];

(hopefully the brackets are correct)

At this point, i dont think there's anyone interested in answering my question, so i'll just post the workaround that i did:

In the 404 page of the application, commented out the entire template content (so if the user has slow connection and is redirected to 404, he doesn't see anything). I also added a redirect in the before created lifecycle hook:

  beforeCreate() {
    this.$router.push({ name: "login" });
  },

This way, the user is automatically redirected to the login with no issues.

Related