Vue · Senior · Question 60 of 75

What is the modern way to redirect or cancel inside a Vue Router 4 guard?

router.beforeEach((to) => {
  if (to.meta.requiresAuth && !auth.loggedIn) return { name: 'login', query: { redirect: to.fullPath } }
})

Explanation

Returning values avoids bugs like calling next() twice or never. Guards can also be async functions.

Further reading

Problem with a question

Vue · Senior · question 60

Test yourself

Take the Vue · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz