Home > other >  Browser shows requested page before redirecting with beforeEach in Vue Router
Browser shows requested page before redirecting with beforeEach in Vue Router

Time:02-25

In my Vue 3 app (based on Quasar 2) I have setup a global navigation guard. This call an external API endpoint to check if the user is logged in. If not, then the user gets redirected to the authentication provider's login form.

The following code works and does what it's supposed to to do. However, when the user is not authenticated, then the browser shows the originally requested page for something less than a second before redirecting.

I don't understand where this comes from and how to resolve it, i.e. that the user shall get redirected instantly without the browser shortly showing the app's page.

import { boot } from 'quasar/wrappers';
import useUserInfoStore from 'src/stores/userInfo';
import userClient from 'src/api/userClient';

export default boot(({ router }) => {
  const userInfoStore = useUserInfoStore();
  // try to access the current user's information to check if authenticated
  router.beforeEach(() => {
    userClient.getUserInfo().then((response) => {
      userInfoStore.authenticated = true;
    }).catch((e) => {
      // otherwise, assume that the user hasn't authenticated and redirect to auth provider
      if (e.response.status === 401) {
        userInfoStore.$reset();
        window.location.href = 'http://localhost:8500/oauth2/authorization/keycloak';
      }
    });
  });
});

CodePudding user response:

What happens is:

  1. beforeEach is called
  2. userClient.getUserInfo() immediately returns a promise
  3. beforeEach immediately returns undefined and router continues navigation
  4. the originally requested page is shown for a couple of moments
  5. the promise resolves in an error and you get redirected to a login page
  • Related