I'm using Vue + SSR on a new project and I'm trying to implement a route guard to enforce authentication on certain routes. I want to do something like this:
function requireAuth(to, from, next) {
if(!store.auth.getters.authenticated){
// redirect to login
}
...
}
However, I can't simply import
the store as in a normal app since I'm creating a fresh instance for each request, inside of a function, as per the official docs.
export function createRouter () {
return new Router({
...
});
}
Is there any way of passing the store to the route guard? Or am I coming at this from completely the wrong angle? Any help is greatly appreciated!
Ok, I found a solution, but it's not the most elegant. Inspired by this comment on GitHub...
And don't forget to pass the store into the createRouter function:
Also make sure to avoid / mitigate any browser-only code in the underlying logic.