I encountered a similar issue and managed to come up with a working solution for production:
router.beforeEach((to, from, next) => {
let requiresAuth = (to.meta.hasOwnProperty('requiresAuth') ? to.meta.requiresAuth : true);
//... explanation
if (!store.getters.isAuthenticated() && requiresAuth) {
next({name: 'login', params: {...{redirect: to.name}, ...to.params}});
return;
} else if (store.getters.isAuthenticated() && !store.getters.isDataPreloaded() && to.name !== 'preloading') {
//... explanation
next({name: 'preloading', params: {...{redirect: to.name}, ...to.params}});
return;
}
next();
})
Whether you choose to utilize query or params is up to you. Optionally, you can include parameters to indicate certain actions during redirection. By adding an optional param
like redirected
, you can differentiate between actions in your beforeEach
method.
Keep in mind that the params
property allows exchanging data between routes without revealing it in URLs to users.
Here's a breakdown of why and how my code functions:
- User accesses page
example.com/my-private-zone/dashboard/reports
- System checks authentication status; if not authenticated, saves current route as
from
and redirects to login page example.com/login
.
- User successfully authenticates
- User gets redirected to
preloading
page (example.com/preloading
) for JS script preloading.
- Finally, user returns to initial route from step 1, passing entry point as
redirect
param for seamless redirect without URL changes.
Your code should also work fine, but don't forget to include a return
statement within your if
branch:
router.beforeEach((to, from, next) => {
if (from.query.userId) {
next({
path: to.path,
query: Object.assign({}, to.query, from.query.userId),
})
return;
}
next()
})
I hope this clarification is helpful!