'Browser shows requested page before redirecting with beforeEach in Vue Router
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';
}
});
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
