Skip to content

Replace state on client happens after beforeEach router hook  #105

Open
@oshnix

Description

@oshnix

I want some unauthorized users to prevent from visiting pages on site.
I added beforeEach hook for each route that looks like

//main.js
router.beforeEach((to,from,next) => {
	let authorized = store.state.user !== null;
        if(to.matched.some(record => record.meta.auth === true)){ 
    		if(!authorized){
			    next({ name: 'Error', params: [to.path], replace: true });
		    }
	    }
       next();
});

And it works for me just fine but when it comes to user side it looks like this hook work before replacing local store state with server side fetched data.
So the page always redirects me to error and I get plenty of warnings about DOM tree not matching server rendered DOM.
The only idea I have is to replace state just after creating store so createApp function will look something like this:

export function createApp() {
	const store = createStore();
	if(SERVER === false && window.__INITIAL_STATE__){
		store.replaceState(window.__INITIAL_STATE__);
	}
	const router = createRouter();
	router.beforeEach((to,from,next) => {
		let authorized = store.state.user !== null;
		if(to.matched.some(record => record.meta.auth === true)){
			if(!authorized){
				next({ name: 'Error', params: [to.path], replace: true });
			}
		}
		next();
	});
	const app = new Vue({
		router,
		store,
		render: h => h(App)
	});
	return {app, router, store};
}

But it doesn't look good. If there's a way to do it right?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions