The "beforeEnter" option for routes doesn't work correctly!

In my web application with “browserHistory” enabled, the “beforeEnter” option is only executed while navigating between routes. I would like that, when reloading the page from any route, the “beforeEnter” is executed to check if the user is authenticated and redirect him to the login route, but this is not happening.

What am I doing wrong?

Here is my example code:

function checkAuth({ resolve, reject }) {
	const token = localStorage.getItem('@token');
	if (!token) this.navigate('/sign-in');
	if (!token) return reject();
	return resolve();
}

const routes = [
	{
		path: '/',
		component: PageHome,
		beforeEnter: checkAuth,
	},
	{
		path: '/city',
		component: PageCity,
		beforeEnter: checkAuth,
	},
	{
		path: '/place',
		component: PagePlace,
		beforeEnter: checkAuth,
	},
	{
		path: '/sign-in',
		component: PageSignIn,
	},
	{
		path: '(.*)',
		component: Page404,
	},
];

here => angry-lumiere-t9trjt - CodeSandbox

1 Like

I can’t believe you actually managed to make it work! Thank you very much!!! :blush:

Looking at your example, to make the “beforeEnter” run, all you had to do was put the component to render using the “async” parameter, as shown in the code snippet below:

{
	path: '/my-page',
	beforeEnter: [checkAuth],
	async: ({ resolve }) => resolve({ component: MyPage }),
}